Memoization with Map for Better Keys
You'll learn why Map is superior to plain objects for memoization caches when your function arguments aren't simple strings.
The Problem with Object Caches
In earlier memoization examples, you might have used a plain object as a cache with string keys. But what if your function accepts objects or arrays as arguments? Converting them to strings creates collisions:
// ❌ Problem: both calls produce the same string key
JSON.stringify({a: 1, b: 2}) // '{"a":1,"b":2}'
JSON.stringify({b: 2, a: 1}) // '{"b":2,"a":1}' - different!
Even worse, different object instances with identical values would miss the cache because [1,2].toString() and [1,2].toString() produce the same string but represent different calls.
Using Map for Identity-Based Keys
Map allows you to use any value as a key — including objects and arrays — using reference equality:
function memoizeWithMap(fn) {
const cache = new Map();
return function(arg) {
if (cache.has(arg)) {
console.log('Cache hit!');
return cache.get(arg);
}
const result = fn(arg);
cache.set(arg, result);
return result;
};
}
const expensiveProcess = memoizeWithMap(obj => {
return obj.value * 2;
});
const config = {value: 10};
expensiveProcess(config); // Calculates
expensiveProcess(config); // Cache hit! (same reference)
const config2 = {value: 10};
expensiveProcess(config2); // Calculates (different reference)
Here, the Map uses the object reference itself as the key. Same object? Cache hit. Different object? New calculation, even if contents match.
Key Takeaway: Use Map instead of objects for memoization caches when dealing with non-primitive arguments; it preserves reference identity and avoids string conversion pitfalls.