Dependency Graph Topological Sort
Topologically sort a dependency graph with Kahn algorithm and detect cycles that make an ordering impossible.
Code
export function topologicalSort(graph: ReadonlyMap<string, readonly string[]>): string[] {
const indegree = new Map<string, number>();
const nodes = new Set<string>(graph.keys());
for (const deps of graph.values()) for (const dep of deps) nodes.add(dep);
for (const node of nodes) indegree.set(node, 0);
for (const [, deps] of graph) for (const dep of deps) indegree.set(dep, (indegree.get(dep) ?? 0) + 1);
const queue: string[] = [];
for (const [node, degree] of indegree) if (degree === 0) queue.push(node);
const order: string[] = [];
while (queue.length > 0) {
const node = queue.shift() as string;
order.push(node);
for (const dep of graph.get(node) ?? []) {
const next = (indegree.get(dep) ?? 0) - 1;
indegree.set(dep, next);
if (next === 0) queue.push(dep);
}
}
if (order.length !== nodes.size) throw new Error('dependency graph contains a cycle');
return order;
}Report a problem with this exampleOpens a pre-filled issue on GitHub.