Graph DFS Topological Sort Typed
Perform topological sort on a typed DAG using DFS with cycle detection via tri-color marking.
Code
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 === GRAYshort-circuits the flow with an earlythrowwhen 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
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
- 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.