const userCache = new WeakMap();
function cacheUserData(userId, data) {
// userId is a number β WeakMap keys must be objects!
userCache.set(userId, data); // TypeError!
return data;
}
function getUserData(userId) {
return userCache.get(userId);
}
cacheUserData(42, { name: 'Alice' });// Option 1: Use a regular Map (if userId is a primitive)
const userCache = new Map();
function cacheUserData(userId, data) {
userCache.set(userId, data); // β
Map accepts any key type
return data;
}
// Option 2: Use WeakMap keyed by the user OBJECT (not its ID)
const userObjCache = new WeakMap();
function cacheUser(userObj, computedData) {
userObjCache.set(userObj, computedData); // userObj is an object β
return computedData;
}
// Option 3: If you need number IDs and auto-cleanup, wrap in an object
const keyRegistry = new Map(); // id β wrapper object
function getKey(id) {
if (!keyRegistry.has(id)) keyRegistry.set(id, { id });
return keyRegistry.get(id);
}
const cache = new WeakMap();
cache.set(getKey(42), { name: 'Alice' });Bug: WeakMap only accepts objects (or registered symbols) as keys. Primitives like numbers, strings, booleans throw TypeError.
Explanation: WeakMap requires object keys so it can hold weak references (GC can collect them). Primitives are not GC'd β they don't need weak references. Use Map for primitive keys.
Key Insight: WeakMap keys must be objects. For primitive keys (string, number), use a regular Map. Use WeakMap when the key is an object and you want automatic cleanup when the object is GC'd.