Clear memoization caches to avoid leaks
Clear memoization caches to avoid leaks in JavaScript by bounding the Map, evicting the oldest entries as new ones arrive. Works in any Node.js.
A memoize wrapper that never forgets will grow with every new input. For a long-running server that is a slow memory leak, so give the cache a limit.
const memoize = (fn, max = 2) => {
const cache = new Map();
return (key) => {
if (cache.has(key)) {
const value = cache.get(key);
cache.delete(key);
cache.set(key, value);
return value;
}
const value = fn(key);
cache.set(key, value);
if (cache.size > max) cache.delete(cache.keys().next().value);
return value;
};
};
let calls = 0;
const double = memoize((n) => {
calls++;
return n * 2;
});
double(1);
double(2);
double(3);
double(1);
console.log(calls);4With room for two entries, adding 3 evicted 1, the oldest, so the later call for 1 had to compute again: four calls for four requests, and no hits. A hit moves its key to the end of the Map, so the first key is always the least recently used.
Choose the limit from how much memory a result takes and how often keys repeat. If keys are objects, a WeakMap frees entries by itself, but it cannot be limited or cleared in bulk. Without a bound, at least expose a clear() and call it when the data it depends on changes.