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.
Code
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: undefinedWhat 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
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.