javascript / intermediate
Snippet
Memory-Safe Metadata with WeakMap
WeakMap holds 'weak' references to keys, which must be objects. If no other references to the key object exist, it can be garbage collected even if it is still a key in the WeakMap. This prevents memory leaks when storing metadata about objects.
snippet.js
1
2
3
4
5
6
7
8
const tracker = new WeakMap();function process(obj) {if (!tracker.has(obj)) tracker.set(obj, { count: 0 });tracker.get(obj).count++;}let data = { task: 'clean' };process(data);data = null;
Breakdown
1
const tracker = new WeakMap();
Initializes a map where keys are garbage-collectable objects.
2
tracker.set(obj, { count: 0 });
Associates metadata with the object without preventing its deletion from memory.
3
data = null;
Clearing the reference allows the object and its associated WeakMap entry to be deleted.