WeakMap keyed by object, GC-friendly
A WeakMap only accepts objects as keys, and holds them *weakly* when no other reference to the key object exists, the entry is automatically removed by the garbage collector. This prevents the WeakMap from becoming a memory leak.
const cache = new WeakMap()
function processUser(user) {
if (cache.has(user)) {
return cache.get(user) // reuse cached result
}
const result = expensiveCompute(user)
cache.set(user, result)
return result
}
let user = { id: 1, name: "Alice" }
processUser(user)
// When user is no longer referenced, the WeakMap entry
// is automatically eligible for garbage collection:
user = null // GC can now clean up the entry