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.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.