WeakSet Tracks Objects Without Keeping Them

WeakSet records which objects a traversal has handled without pinning them in memory, rejects primitives, and exposes no size or iteration surface.

JavascriptResilience

Code

javascriptsnippet
29 lines
const seen = new WeakSet();

function process(node) {
  if (seen.has(node)) {
    console.log('skip already-seen:', node.id);
    return;
  }
  seen.add(node);
  console.log('visited:', node.id);
}

// Walk a graph while remembering which objects were handled. WeakSet entries
// do not keep the objects alive, so collectors can reclaim them later.
const a = { id: 'a' };
const b = { id: 'b' };
process(a);
process(b);
process(a);

// Only objects may be stored; primitives are rejected outright
try {
  seen.add('a-string');
} catch (err) {
  console.log('primitive rejected:', err instanceof TypeError);
}

// WeakSet is not enumerable: no size, no iteration methods
console.log('no size:', seen.size === undefined);
console.log('no forEach:', typeof seen.forEach);

Output

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

visited: a
visited: b
skip already-seen: a
primitive rejected: true
no size: true
no forEach: undefined

What the code does

One way to read it: the function process, doing all the work.

What to watch for

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

Applying it

One line captures it: function process(node)

Look for the skip already-seen:, visited:, primitive rejected: prefixes when the file runs; they tie each line to its step.

Statements that matter

const seen = new WeakSet();
const a = { id: 'a' };
const b = { id: 'b' };

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `process` at load time.