Memoize a function with a Map
Memoize a function in JavaScript with a Map keyed by its argument, caching results including undefined. For single-argument pure functions on any Node.js.
A pure function with the same input always gives the same output, so computing it twice is waste. Keep each result in a Map and return it on the next call.
const memoize = (fn) => {
const cache = new Map();
return (arg) => {
if (cache.has(arg)) return cache.get(arg);
const value = fn(arg);
cache.set(arg, value);
return value;
};
};
let calls = 0;
const square = memoize((n) => {
calls++;
return n * n;
});
square(4);
square(4);
square(5);
console.log(calls, square(4));2 16cache.has is used instead of testing the value, so a result of undefined or 0 is cached rather than recomputed. A Map accepts any value as a key, with NaN equal to NaN.
It only works for one argument and a pure function. For several arguments, build a key with JSON.stringify(args), which is slower and breaks on values JSON cannot represent. The cache also never shrinks, so see the snippet on clearing memoization caches before using it on unbounded input.