Memoize with a WeakMap for object arguments
Memoize a function in JavaScript with a WeakMap when its argument is an object, so cached results are dropped with the object. Works in any Node.js.
A Map cache holds its keys forever. When the key is an object, such as an order or a DOM node, that keeps the object alive after nothing else uses it. A WeakMap lets both go together.
const memoizeByObject = (fn) => {
const cache = new WeakMap();
return (obj) => {
if (!cache.has(obj)) cache.set(obj, fn(obj));
return cache.get(obj);
};
};
let runs = 0;
const total = memoizeByObject((order) => {
runs++;
return order.items.reduce((sum, item) => sum + item.price, 0);
});
const order = { items: [{ price: 5 }, { price: 7 }] };
total(order);
total(order);
total({ items: [{ price: 5 }, { price: 7 }] });
console.log(total(order), runs);12 2The second call with order is a hit. The third call has equal contents but is a different object, so it is a miss, and that is why runs ends at 2. A WeakMap holds its keys weakly, so when an order is garbage collected its cached total goes with it.
Keys must be objects, and a WeakMap cannot be iterated or cleared in one call. If the object is mutated after caching, the old result is returned, so use this for objects treated as immutable.