Dependency Graph Topological Sort

Topologically sort a dependency graph with Kahn algorithm and detect cycles that make an ordering impossible.

TypescriptData Integrity

Code

typescriptsnippet
22 lines
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.size short-circuits the flow with an early throw when 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

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.