Review a generated dependency order

from Trees and graphs
Node 24 intermediate 9 min 4 issues to find

Review this generated helper before the deployment service accepts external dependency graphs.

Return every reachable dependency before the service that needs it, support several roots, and reject missing services and cycles.

JavaScript
function buildInstallOrder(graph, roots) {
  const visited = new Set();
  const order = [];

  function visit(service) {
    if (visited.has(service)) return;
    visited.add(service);

    const dependencies = graph.get(service);
    for (const dependency of dependencies) {
      visit(dependency);
    }

    if (!order.includes(service)) {
      order.push(service);
    }
  }

  for (const root of roots) {
    visit(root);
  }

  return order;
}

generated code is illustrative, not from any one model

Open in playground
Report an error