Graph DFS Topological Sort Typed

Perform topological sort on a typed DAG using DFS with cycle detection via tri-color marking.

TypescriptData Integrity

Code

typescriptsnippet
16 lines
function topologicalSort(graph: Map<string, string[]>): string[] {
  const WHITE = 0, GRAY = 1, BLACK = 2;
  const color = new Map<string, number>();
  const result: string[] = [];
  for (const n of graph.keys()) color.set(n, WHITE);
  function dfs(node: string): void {
    const c = color.get(node)!;
    if (c === GRAY) throw new Error("cycle at " + node);
    if (c === BLACK) return;
    color.set(node, GRAY);
    for (const neighbor of graph.get(node) ?? []) dfs(neighbor);
    color.set(node, BLACK); result.push(node);
  }
  for (const n of graph.keys()) if (color.get(n) === WHITE) dfs(n);
  return result.reverse();
}

How it works

Count the functions topologicalSort and dfs as the entire surface area of Graph DFS Topological Sort Typed.

The nesting pairs for (const n of graph.keys()) color.set(n, WHITE); with for (const neighbor of graph.get(node) ?? []) dfs(neighbor); — the inner runs once per outer step. Error is the guard’s signal — thrown at the branch, before any partial work happens.

Caveats

  • The guard c === GRAY short-circuits the flow with an early throw when its condition holds.

Putting it to use

The primary signature is function topologicalSort(graph: Map<string, string[]>)

Core lines

for (const neighbor of graph.get(node) ?? []) dfs(neighbor);
if (c === GRAY) throw new Error("cycle at " + node);
const color = new Map<string, number>();

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
The code refuses to continue: `Error` is thrown while the state is still recoverable.
Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `topologicalSort`, `dfs` at load time.