WeakSet Records Visited Nodes Transiently

Track which objects a traversal has touched with WeakSet — members can be garbage collected, so the bookkeeping never pins the graph in memory.

JavascriptData Integrity

Code

javascriptsnippet
33 lines
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');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

reachable: 3
tracked object identity is preserved: true

Walkthrough of the flow

WeakSet Records Visited Nodes Transiently is built around the class Node and the functions walk and countReachable.

Caveats

  • The package manager never enters the picture for this snippet.

Putting it to use

Entry signature: const walk = (node)

The demo output is labeled (reachable:, tracked object identity is preserved:), so reading the output replays the steps in order.

The central lines

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

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `walk`, `countReachable` at load time.