Graph DFS Topological Sort (JavaScript)
Perform topological sort on a directed acyclic graph using depth first search with cycle detection via a tri-color marking scheme.
Code
function topologicalSort(graph) {
const WHITE = 0, GRAY = 1, BLACK = 2;
const color = new Map();
const result = [];
const nodes = Object.keys(graph);
for (const n of nodes) color.set(n, WHITE);
function dfs(node) {
if (color.get(node) === GRAY) throw new Error("cycle detected at " + node);
if (color.get(node) === BLACK) return;
color.set(node, GRAY);
for (const neighbor of graph[node] || []) dfs(neighbor);
color.set(node, BLACK);
result.push(node);
}
for (const n of nodes) if (color.get(n) === WHITE) dfs(n);
return result.reverse();
}How the snippet works
The working surface is the functions topologicalSort and dfs — everything else is wiring.
The nesting pairs for (const n of nodes) color.set(n, WHITE); with for (const neighbor of graph[node] || []) dfs(neighbor); — the inner runs once per outer step. Invalid states are rejected up front: it throws Error instead of continuing with bad data.
Using it
The primary signature is function topologicalSort(graph)
Key statements
if (color.get(node) === GRAY) throw new Error("cycle detected at " + node);
const color = new Map();
return result.reverse();
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
- Does the code validate its input?
- Validation comes first — `Error` marks the failure, before any partial work happens.
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `topologicalSort`, `dfs` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.