← 中文资源

简体中文版本

带环检测的拓扑排序(JavaScript)

对依赖图排序,使每个节点都排在其前置节点之后,并在无法形成有效顺序时报告环。

阅读英文原文

实现说明

除了函数 visit、topologicalSort,文件里再无其他定义。 迭代是嵌套的:for (const dep of graph.get(node) ?? []) visit(dep); 框定这一趟,for (const node of graph.keys()) visit(node); 做逐项处理。失败路径是显式的——守卫条件成立就抛出 Error。

使用要点

  • topologicalSort 是公开入口,文件里其余部分都是为它服务的内部实现。

常见问题

输入不合法时代码会怎么表现?

在真正开工之前就会抛出 Error——请在调用点处理,或有意向上传播。

有语言之外需要解析的导入吗?

没有。每个导入都解析到语言自带的模块。 文件在加载时定义 visit、topologicalSort。

签名一览:export function topologicalSort(graph)

核心语句

if (inStack.has(node)) throw new Error("cycle detected at " + node);
for (const dep of graph.get(node) ?? []) visit(dep);
const visited = new Set();

代码示例

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