Implement a Dependency Graph Resolver From Scratch in JavaScript
Build a dependency graph resolver from scratch in JavaScript with topological sort, cycle detection, missing dependency errors and build layers. Node.js 24.

Every package manager, build tool and task runner answers the same question: given things that depend on other things, in what order do I process them? The answer is a topological sort, and the interview version adds the two failures that make it interesting, a dependency that does not exist and a cycle that makes any valid order impossible. This post builds a dependency graph resolver on Node.js 24 in four steps: a depth-first sort, a clear error for cycles that shows the loop, a check for missing dependencies and a layered version that tells you what can run in parallel. It ends with tests.
The contract
The input is an object that maps each name to the names it depends on, for example { app: ["lib", "utils"], lib: ["utils"], utils: [] }. The output is an array of names in an order where every item appears after everything it depends on: ["utils", "lib", "app"]. Two inputs have no valid answer, a cycle and a reference to a name that is not a key, and the function must report both instead of returning something wrong.
Depth-first topological sort
Visit each node. Before adding a node to the result, visit all of its dependencies. Track which nodes are done so that shared dependencies are processed once.
function resolve(graph) {
const order = [];
const done = new Set();
function visit(name) {
if (done.has(name)) return;
for (const dep of graph[name]) {
visit(dep);
}
done.add(name);
order.push(name);
}
for (const name of Object.keys(graph)) {
visit(name);
}
return order;
}
const graph = {
app: ["lib", "utils"],
lib: ["utils"],
utils: [],
};
console.log(resolve(graph));[ 'utils', 'lib', 'app' ]Trace it. visit("app") visits lib first, which visits utils, which has no dependencies, so utils is pushed, then lib, then back in app the second dependency utils is already done and is skipped, then app is pushed. A name is pushed only after everything below it, which is the post-order property that makes the list a valid build order.
The done set is what keeps the work proportional to the number of nodes plus edges. Without it, a shared dependency reached by many paths would be walked again each time, and a diamond-shaped graph would repeat work exponentially.
What goes wrong with a cycle
Feed it a graph where two nodes depend on each other.
const cyclic = { a: ["b"], b: ["a"] };
// resolve(cyclic) never finishes:
// visit("a") calls visit("b"), which calls visit("a") again,
// because "a" is only added to `done` after its dependencies are visited.
// The recursion runs until the engine throws a RangeError for stack size.The sort does not terminate on its own: each visit starts before the other finishes, so nothing is ever marked done. With the default stack size it ends in RangeError: Maximum call stack size exceeded, which tells the caller nothing about which names form the loop. The fix is a second state. A node is either unvisited, in progress (on the current path) or done. Reaching an in-progress node means the current path loops back on itself.
function resolve(graph) {
const order = [];
const state = new Map();
const path = [];
function visit(name) {
if (state.get(name) === "done") return;
if (state.get(name) === "visiting") {
const start = path.indexOf(name);
const loop = [...path.slice(start), name];
throw new Error(`circular dependency: ${loop.join(" -> ")}`);
}
state.set(name, "visiting");
path.push(name);
for (const dep of graph[name]) {
visit(dep);
}
path.pop();
state.set(name, "done");
order.push(name);
}
for (const name of Object.keys(graph)) {
visit(name);
}
return order;
}
try {
resolve({ a: ["b"], b: ["c"], c: ["a"], d: [] });
} catch (error) {
console.log(error.message);
}circular dependency: a -> b -> c -> aThe path array holds the names on the current route from the root. When visit("a") is reached again while a is still visiting, the loop is the slice of the path from the first a, plus a itself to close it. That message is what you want in a real tool: the user can see which edge to cut. The name d, which is unrelated, never gets visited because the error stops everything at the first cycle found. A tool that wants all cycles needs a stronger algorithm, such as finding strongly connected components, and saying so is a fine answer.
Missing dependencies
The second error is a name nobody defined. In the code above, graph[name] is undefined for it, and for (const dep of undefined) throws TypeError: undefined is not iterable, which is again an unhelpful message. Validate first.
function assertComplete(graph) {
for (const [name, deps] of Object.entries(graph)) {
for (const dep of deps) {
if (!Object.hasOwn(graph, dep)) {
throw new Error(`${name} depends on unknown package ${dep}`);
}
}
}
}
try {
assertComplete({ app: ["lib"], lib: ["left-pad"] });
} catch (error) {
console.log(error.message);
}lib depends on unknown package left-padObject.hasOwn is used instead of dep in graph because in also finds inherited names. A package called constructor or toString would otherwise pass the check, as "constructor" in {} is true. Package names come from outside, so assume hostile or odd ones.
Putting the checks together
function resolveOrder(graph) {
assertComplete(graph);
return resolve(graph);
}
console.log(resolveOrder({ web: ["api", "ui"], api: ["db"], ui: [], db: [] }));[ 'db', 'api', 'ui', 'web' ]The order follows the key order of the input: web is visited first, which visits api, which visits db. Then ui, then web itself. Many valid orders exist, and this one is deterministic because object keys keep insertion order for non-integer names. If the caller needs a stable result regardless of how the object was written, sort the keys and each dependency list before visiting.
Recursion depth
A dependency chain of ten thousand packages makes the recursive version ten thousand frames deep, which can exceed the default stack. Real dependency trees are shallow, but a graph built from generated data can be deep, so the iterative alternative is worth knowing. Kahn's algorithm uses a queue and a count of unmet dependencies.
function kahn(graph) {
assertComplete(graph);
const remaining = new Map();
const dependents = new Map();
for (const [name, deps] of Object.entries(graph)) {
remaining.set(name, deps.length);
for (const dep of deps) {
if (!dependents.has(dep)) dependents.set(dep, []);
dependents.get(dep).push(name);
}
}
const queue = [...remaining].filter(([, n]) => n === 0).map(([name]) => name);
const order = [];
while (queue.length > 0) {
const name = queue.shift();
order.push(name);
for (const next of dependents.get(name) ?? []) {
remaining.set(next, remaining.get(next) - 1);
if (remaining.get(next) === 0) queue.push(next);
}
}
if (order.length !== Object.keys(graph).length) {
const stuck = Object.keys(graph).filter((name) => !order.includes(name));
throw new Error(`circular dependency among: ${stuck.join(", ")}`);
}
return order;
}
console.log(kahn({ app: ["lib", "utils"], lib: ["utils"], utils: [] }));[ 'utils', 'lib', 'app' ]Start with everything that has no unmet dependencies. Each time a node is emitted, reduce the counter of everything that depends on it, and queue the ones that reach zero. If the loop ends with fewer names than the graph holds, the rest are stuck behind a cycle. The error here lists every name that could not be placed, which includes the nodes on the loop and anything that depends on the loop, so it is less precise than the depth-first message.
Layers for parallel work
A build tool does not just want an order. It wants to know what can run at the same time. Group the output of Kahn's algorithm into levels: everything whose dependencies are all in earlier levels forms one level.
function layers(graph) {
assertComplete(graph);
const remaining = new Map(Object.entries(graph).map(([n, d]) => [n, new Set(d)]));
const result = [];
while (remaining.size > 0) {
const ready = [...remaining].filter(([, deps]) => deps.size === 0).map(([n]) => n);
if (ready.length === 0) {
throw new Error(`circular dependency among: ${[...remaining.keys()].join(", ")}`);
}
result.push(ready);
for (const name of ready) remaining.delete(name);
for (const deps of remaining.values()) {
for (const name of ready) deps.delete(name);
}
}
return result;
}
console.log(layers({ web: ["api", "ui"], api: ["db"], ui: ["db"], db: [] }));[ [ 'db' ], [ 'api', 'ui' ], [ 'web' ] ]db has no dependencies, so it is the first layer. After removing it, api and ui are both unblocked, so they form a layer that a tool can run concurrently, for example with Promise.all. web waits for both. The number of layers is the length of the longest dependency chain, which is the minimum number of sequential steps no matter how many workers you have. That is a useful fact to state in the interview.
Using it for real work
Two small additions make this resolver useful beyond an interview. First, accept the dependency lists as arrays or sets, and copy them on the way in, so that later changes to the caller's object cannot alter a build in progress. Second, return the graph's reverse as well, the list of dependents for each name, because the question after "what order?" is almost always "what do I need to rebuild when this one changes?". With the dependents map from Kahn's algorithm, that is a walk from the changed node outward, and the set it reaches is exactly the work an incremental build must redo.
Task runners use the layers directly. Each layer is a batch, started together and awaited together, and a failure in one layer cancels everything after it, since later layers depend on the earlier ones. That is the whole scheduling logic of a simple build system.
Testing it
import test from "node:test";
import assert from "node:assert/strict";
test("dependencies come before dependents", () => {
const order = resolveOrder({ app: ["lib"], lib: ["core"], core: [] });
assert.ok(order.indexOf("core") < order.indexOf("lib"));
assert.ok(order.indexOf("lib") < order.indexOf("app"));
});
test("a cycle names the loop", () => {
assert.throws(() => resolve({ a: ["b"], b: ["a"] }), /a -> b -> a/);
});
test("an unknown dependency is reported", () => {
assert.throws(() => assertComplete({ a: ["zzz"] }), /unknown package zzz/);
});
test("layers group independent work", () => {
assert.deepEqual(layers({ a: [], b: [], c: ["a", "b"] }), [["a", "b"], ["c"]]);
});ℹ tests 4
ℹ pass 4
ℹ fail 0The assertions on order check relative positions and not the whole array, since several valid orders exist and a test should not depend on which one the implementation picks.


