Topological Sort With Cycle Detection (JavaScript)

Order a dependency graph so every node appears after its prerequisites, reporting a cycle when no valid order exists.

JavascriptData Integrity

Code

javascriptsnippet
16 lines
export function topologicalSort(graph) {
  const visited = new Set();
  const inStack = new Set();
  const order = [];
  const visit = (node) => {
    if (inStack.has(node)) throw new Error("cycle detected at " + node);
    if (visited.has(node)) return;
    inStack.add(node);
    for (const dep of graph.get(node) ?? []) visit(dep);
    inStack.delete(node);
    visited.add(node);
    order.push(node);
  };
  for (const node of graph.keys()) visit(node);
  return order;
}

What the code does

Count the functions visit and topologicalSort as the entire surface area of Topological Sort With Cycle Detection (JavaScript).

Iteration is nested: for (const dep of graph.get(node) ?? []) visit(dep); frames the pass, for (const node of graph.keys()) visit(node); does the per-item step. When the guard condition holds, Error is thrown rather than a bogus value returned.

Applying it

The main signature reads export function topologicalSort(graph)

Treat topologicalSort as the API: import it, and ignore the supporting code.

Statements that matter

if (inStack.has(node)) throw new Error("cycle detected at " + node);
for (const dep of graph.get(node) ?? []) visit(dep);
const visited = new Set();

Interactive Tools for This Topic

FAQ

How does the code behave when input is bad?
It throws `Error` before any real work runs — handle it at the call site or let it propagate deliberately.
Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `visit`, `topologicalSort` at load time.