Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Topological sort with cycle detection in JavaScript

111 Topological sort, and naming the cycle when there is one

hard

Order a set of tasks so that every task comes after everything it depends on. Use Kahn's algorithm: count incoming edges, repeatedly take a task with none left, and decrement its dependents. Break ties deterministically so the result is reproducible, and prove that a different tie-break gives a different order that is just as valid. Then handle the case Kahn only half-answers: when the input contains a cycle it stops early and can tell you how many tasks are stuck but not which ones form the loop. Add a depth-first pass that reports the cycle itself, as a path.

Stuck? Three hints, smallest first
  1. 1. Build a map of dependents and a map of incoming counts. Every task with a count of zero is ready.
  2. 2. If you finish with fewer tasks emitted than you started with, whatever is left is inside or downstream of a cycle. That is the detection; it is not the diagnosis.
  3. 3. For the diagnosis, walk depth-first with three colours: untouched, on the current stack, finished. Meeting a node that is on the current stack means the cycle is the slice of the stack from that node onwards.

The answer

function topoSort(nodes, edges, { tieBreak = (a, b) => (a < b ? -1 : a > b ? 1 : 0) } = {}) {
  const dependents = new Map(nodes.map((n) => [n, []]));
  const incoming = new Map(nodes.map((n) => [n, 0]));
  for (const [before, after] of edges) {
    dependents.get(before).push(after);
    incoming.set(after, incoming.get(after) + 1);
  }

  const ready = nodes.filter((n) => incoming.get(n) === 0).sort(tieBreak);
  const done = [];
  while (ready.length) {
    const task = ready.shift();
    done.push(task);
    for (const next of dependents.get(task)) {
      incoming.set(next, incoming.get(next) - 1);
      if (incoming.get(next) === 0) {
        ready.push(next);
        ready.sort(tieBreak);
      }
    }
  }

  if (done.length === nodes.length) return { order: done, done, stuck: [], cycle: null };
  const stuck = nodes.filter((n) => !done.includes(n));
  return { order: null, done, stuck, cycle: findCycle(nodes, dependents) };
}

function findCycle(nodes, dependents) {
  const UNTOUCHED = 0;
  const ON_STACK = 1;
  const FINISHED = 2;
  const colour = new Map(nodes.map((n) => [n, UNTOUCHED]));
  const stack = [];
  let found = null;

  const visit = (node) => {
    colour.set(node, ON_STACK);
    stack.push(node);
    for (const next of dependents.get(node)) {
      if (found) break;
      if (colour.get(next) === ON_STACK) {
        found = [...stack.slice(stack.indexOf(next)), next];
        break;
      }
      if (colour.get(next) === UNTOUCHED) visit(next);
    }
    stack.pop();
    colour.set(node, FINISHED);
  };

  for (const node of nodes) {
    if (found) break;
    if (colour.get(node) === UNTOUCHED) visit(node);
  }
  return found;
}

const tasks = ['fitOut', 'hire', 'insurance', 'launch', 'lease', 'permit', 'signage', 'stock', 'train'];
const before = [
  ['lease', 'fitOut'],
  ['permit', 'fitOut'],
  ['fitOut', 'stock'],
  ['stock', 'launch'],
  ['hire', 'train'],
  ['train', 'launch'],
  ['permit', 'signage'],
  ['signage', 'launch'],
];

const forwards = topoSort(tasks, before);
const edgesGoForwards = (order, list) =>
  list.every(([a, b]) => order.indexOf(a) < order.indexOf(b));
const forwardsValid = [edgesGoForwards(forwards.order, before), forwards.order.length, forwards.order.includes('insurance')];

const backwards = topoSort(tasks, before, { tieBreak: (a, b) => (a < b ? 1 : a > b ? -1 : 0) });
const bothValid = [edgesGoForwards(backwards.order, before), same(backwards.order, forwards.order)];

const withCycle = topoSort(tasks, [...before, ['launch', 'permit']]);
const kahnGaveUp = [withCycle.order, withCycle.done, withCycle.stuck.length];

const reported = withCycle.cycle;
const cycleIsReal = (() => {
  const pairs = [...before, ['launch', 'permit']].map(([a, b]) => a + '->' + b);
  let everyStepIsAnEdge = true;
  for (let i = 1; i < reported.length; i++) {
    if (!pairs.includes(reported[i - 1] + '->' + reported[i])) everyStepIsAnEdge = false;
  }
  return [everyStepIsAnEdge, reported[0] === reported[reported.length - 1]];
})();

const selfLoop = topoSort(['audit'], [['audit', 'audit']]);

console.log('alphabetical  :', forwards.order.join(' '));
console.log('reverse       :', backwards.order.join(' '));
console.log('with a cycle  :', withCycle.done, 'stuck:', withCycle.stuck);
console.log('the cycle     :', reported.join(' -> '));

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('every task lands after everything it depends on, tie-broken alphabetically', forwards.order, ['hire', 'insurance', 'lease', 'permit', 'fitOut', 'signage', 'stock', 'train', 'launch']);
test('checked directly against every edge, and the task with no edges is still in there', forwardsValid, [true, 9, true]);
test('a reverse tie-break gives a different order that is equally valid', bothValid, [true, false]);
test('reversing the tie-break really does change the order', backwards.order, ['permit', 'signage', 'lease', 'insurance', 'hire', 'train', 'fitOut', 'stock', 'launch']);
test('one extra edge makes a cycle, and Kahn returns no order at all', kahnGaveUp, [null, ['hire', 'insurance', 'lease', 'train'], 5]);
test('the depth-first pass names the loop as a path that returns to its start', reported, ['fitOut', 'stock', 'launch', 'permit', 'fitOut']);
test('and every step of that path is a real edge, first node equal to last', cycleIsReal, [true, true]);
test('a task that depends on itself is a cycle of length two, and nothing can run', [selfLoop.cycle, selfLoop.done, selfLoop.order], [['audit', 'audit'], [], null]);

Kahn's algorithm is a counting argument. A task with no unmet dependencies can run now; running it removes one dependency from each of its dependents; anything that drops to zero joins the ready set. When the ready set empties, either everything has run or what remains is holding itself up. The termination condition is the cycle detection, which is why you get it for free.

What you do not get for free is which tasks form the loop, and the fifth assertion shows the gap: five tasks are stuck, but only four of them are in the cycle — signage is merely downstream of it. Telling a user "5 tasks could not be ordered" is unhelpful; telling them fitOut → stock → launch → permit → fitOut is a bug report. That needs the depth-first pass, and the trick is the three colours. A node coloured on stack is an ancestor of where you are now, so an edge to it closes a loop, and the loop is exactly the slice of the stack from that node to the top.

The third and fourth assertions are the honest caveat about topological order: it is not unique. Any order satisfying every edge is correct, and there are usually many. That matters because a build tool whose task order changes between runs is very hard to debug, so real implementations pin the tie-break — alphabetical, declaration order, anything — and the sorted ready list here is that pin. Note also what an unstable ready set would cost you: the same input would produce different output on different engines, since Array.prototype.sort was only required to be stable from ES2019.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.