实现说明
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');