Sub topic 15
WeakSet Fundamentals and Object Tagging
This chapter assumes you already know the Set API and the rules for weak collections from earlier chapters: weak collections accept only objects and non-registered symbols as entries, and they have no size and no iteration. It also assumes you know what reachability means for garbage collection.
What a WeakSet Is
A WeakSet is a collection of objects in which each object appears at most once. It holds those objects weakly. If the WeakSet is the only thing that still refers to an object, the garbage collector can reclaim that object, and the object then quietly disappears from the set.
A WeakSet answers one question: "Have I seen this object?" It stores no value alongside the entry. If you need to attach data to an object, use a WeakMap instead.
| Feature | Set | WeakSet |
|---|---|---|
| Entry types | Any value | Objects and non-registered symbols |
| Holds entries | Strongly | Weakly |
| Methods | `add`, `has`, `delete`, `clear`, iteration, composition | `add`, `has`, `delete` |
| `size` | Yes | No |
| Typical use | Unique values you list or count | Marking objects |
The API
The API has three methods. add returns the WeakSet, so you can chain calls.
const seen = new WeakSet();
const a = { name: 'a' };
const b = { name: 'b' };
seen.add(a).add(b);
console.log(seen.has(a)); // true
console.log(seen.delete(b)); // true
console.log(seen.has(b)); // false
console.log(seen.has({ name: 'a' })); // false: a different objectMembership is checked by reference. An object with the same contents is still a different entry.
Pattern: Tracking Visited Nodes
Graph traversal has to stop at cycles. A WeakSet records which nodes the traversal has already visited. It does not keep those nodes alive after the graph is discarded.
const visited = new WeakSet();
function walk(node) {
if (visited.has(node)) return;
visited.add(node);
for (const child of node.children) {
walk(child);
}
}
const root = { children: [] };
root.children.push(root); // cycle
walk(root); // terminates
console.log(visited.has(root)); // truePattern: Tagging Objects
Tagging means marking an object as having some status without changing the object itself. The status might be "validated", "already processed", or "created by this class". The tag lives outside the object, so nobody can forge it by adding a property.
const validated = new WeakSet();
function validate(order) {
if (order.items.length === 0) {
throw new Error('Empty order');
}
validated.add(order);
return order;
}
function ship(order) {
if (!validated.has(order)) {
throw new Error('Order not validated');
}
return `Shipping order ${order.id}`;
}
const order = { id: 7, items: ['book'] };
try {
ship(order);
} catch (err) {
console.log(err.message); // 'Order not validated'
}
validate(order);
console.log(ship(order)); // 'Shipping order 7'The same technique can confirm that a value is a real instance of a class. An instanceof check can be fooled by Object.create(Token.prototype). A WeakSet check cannot.
const tokens = new WeakSet();
class Token {
constructor() {
tokens.add(this);
}
static isToken(value) {
return tokens.has(value);
}
}
const fake = Object.create(Token.prototype);
console.log(fake instanceof Token); // true
console.log(Token.isToken(fake)); // false
console.log(Token.isToken(new Token())); // trueCommon Errors
- Calling
seen.add('id')throws aTypeError, because strings are primitives. - A WeakSet can't be listed or counted. If you need to report which objects you processed, use a Set and remove the entries yourself when you are done with them.
- The tag belongs to one specific object. Copying an object with spread or
structuredCloneproduces a new object that has no tag.
Exercise
You tag objects with a WeakSet called processed. Later you run const copy = { ...item }; on a tagged item. What does processed.has(copy) return, and why?
Show answer
It returns false. WeakSet membership is checked by object reference, and spreading creates a new object. The tag belongs only to the original item.
Exercise
Why does a visited-node tracker built on a WeakSet use less memory over time than one built on a Set when many graphs are created and discarded?
Show answer
A Set holds strong references, so every node it has ever recorded stays reachable and can't be collected. A WeakSet holds its entries weakly. Once a discarded graph has no other references, its nodes can be garbage collected, and they drop out of the WeakSet automatically.