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.

JavascriptData Integrity

Code

javascriptsnippet
17 lines
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

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.