Sometimes you need to attach extra data to a DOM node — a cached measurement, a parsed config, a "seen" flag — without writing it onto the element itself. The catch: when that node leaves the page and nothing else references it, your stored data must not keep it alive. Implement nodeRegistry(), which returns a small object that associates arbitrary values with DOM nodes and lets those nodes be garbage-collected once they are gone. The implementation detail that makes this safe is a WeakMap, which holds its keys weakly.
function nodeRegistry(): {
set(node: Node, value: unknown): void; // associate value with node
get(node: Node): unknown; // value, or undefined if absent
has(node: Node): boolean; // is this node registered?
delete(node: Node): boolean; // remove; true if it existed
};
Keys are DOM nodes, compared by identity. Values can be anything. The registry exposes no way to list or count the nodes it holds.
const reg = nodeRegistry();
const a = document.createElement('div');
const b = document.createElement('div');
reg.set(a, { clicks: 1 });
reg.set(b, { clicks: 9 });
reg.get(a); // → { clicks: 1 } (each node keeps its own value)
reg.has(b); // → true
reg.delete(a); // → true
reg.get(a); // → undefined
const reg = nodeRegistry();
const node = document.createElement('span');
reg.get(node); // → undefined (never registered)
reg.set(node, 0);
reg.has(node); // → true (a stored 0 is still "present")
0, false, null — all valid. has reports presence, not truthiness.size, keys(), or forEach — exposing one would defeat the whole point.document.createElement and never inserted is a valid key.