javascript / intermediate
Snippet
Memory-Safe Metadata with WeakMap
WeakMap allows you to associate data with an object without preventing that object from being garbage collected, making it ideal for managing private state or metadata.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
const userMetadata = new WeakMap();function setMetadata(user, data) {userMetadata.set(user, data);}function getMetadata(user) {return userMetadata.get(user);}// When 'user' object is garbage collected,// the entry in userMetadata is also removed.
Breakdown
1
new WeakMap();
Initializes a collection where keys must be objects and are held weakly.
2
userMetadata.set(user, data);
Attaches data to the user object without modifying the object itself.