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;
}Inside the snippet
Dependency Graph Topological Sort keeps everything in the functions next and topologicalSort.
The core work runs in nested loops — outer for (const deps of graph.values()) for (const dep of deps) nodes.add(dep);, inner for (const node of nodes) indegree.set(node, 0);. The failure path is explicit — Error is raised when the guard condition holds.
What to watch for
- The guard
order.length !== nodes.sizeshort-circuits the flow with an earlythrowwhen its condition holds.
Putting it to use
The primary signature is export function topologicalSort(graph: ReadonlyMap<string, readonly string[]>)
topologicalSort is what another module would consume; nothing else here is load-bearing for callers.
Core lines
for (const [, deps] of graph) for (const dep of deps) indegree.set(dep, (indegree.get(dep) ?? 0) + 1);
if (order.length !== nodes.size) throw new Error('dependency graph contains a cycle');
const nodes = new Set<string>(graph.keys());
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How does the code behave when input is bad?
- The code throws `Error` — the guard `order.length !== nodes.size` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `next`, `topologicalSort` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.