Write a memoize with a cache size limit
Write a memoize with a cache size limit in JavaScript, evicting the oldest entry from a Map once it passes the cap. Node.js 24, no libraries.
An unbounded cache is a memory leak with a nice name. A Map remembers insertion order, so the first key is always the oldest and easy to evict.
const memoize = (fn, limit = 2) => {
const cache = new Map();
return (arg) => {
if (cache.has(arg)) return cache.get(arg);
const result = fn(arg);
cache.set(arg, result);
if (cache.size > limit) cache.delete(cache.keys().next().value);
return result;
};
};
let runs = 0;
const square = memoize((n) => (runs++, n * n));
square(2); square(3); square(2);
console.log(runs);
square(4); square(2);
console.log(runs);2
4The first three calls compute 2 and 3 once each, and the third is a hit, so runs is 2. Adding 4 pushes the size to three, which evicts 2, the oldest. The next call for 2 must compute again, so runs becomes 4. Order of keys in a Map follows insertion.
This is first-in, first-out, not least recently used: a hit does not refresh the entry. Move the key to the end on every hit if you need LRU. Keys are compared by identity for objects, so it suits primitives.