审查生成的依赖顺序

来自 树与图
Node 24 进阶 9分钟 找出 4处问题

请在部署服务接收外部依赖图之前,审查这段生成的辅助代码。

让每个可达依赖项都排在需要它的服务之前,支持多个根,并拒绝缺失服务和环。

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;
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误