← 中文资源

简体中文版本

WeakSet 记录已访问节点

遍历图时用 WeakSet 做已访问标记:循环引用被挡住,条目可以随时被垃圾回收,记账本身不会把整个图钉在内存里,适合遍历大图或临时对象。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

reachable: 3
tracked object identity is preserved: true

实现说明

WeakSet 记录已访问节点可以归结为类 Node和函数 walk、countReachable。

使用要点

  • 直接运行文件,输出会带上标签,比如 reachable:、tracked object identity is preserved:——输出的每一行都能指回产生它的那次调用。

常见问题

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

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

签名一览:const walk = (node)

核心语句

const walk = (node) => {
  if (visited.has(node)) return; // cycle guard without leaking memory
  visited.add(node);
  count++;
  node.links.forEach(walk);
};

代码示例

class Node {
  constructor(id) {
    this.id = id;
    this.links = [];
  }
}

function countReachable(root) {
  const visited = new WeakSet();
  let count = 0;

  const walk = (node) => {
    if (visited.has(node)) return; // cycle guard without leaking memory
    visited.add(node);
    count++;
    node.links.forEach(walk);
  };

  walk(root);
  return count;
}

const a = new Node('a');
const b = new Node('b');
const c = new Node('c');
a.links.push(b, c);
b.links.push(c, a); // cycle: a and c are revisited on purpose
c.links.push(a);

console.log('reachable:', countReachable(a));

// WeakSet holds the nodes only weakly: nothing here is kept alive by it.
console.log('tracked object identity is preserved:', typeof a.id === 'string');