Memoize a function
You call an expensive fibonacci(30) and wait. A moment later you need it again
and wait the same amount, even though nothing about the argument changed. The same
work is being thrown away and redone.
The fix is to remember what a call returned. The first call with a given argument
runs the function and stores the result; every later call with the same argument
returns the stored result. That pattern is called memoize: a cache keyed by
argument.
The shape keeps a cache in a closure. On each call, check whether the argument is already a key; if not, compute and store it:
function memoize(fn) {
const cache = new Map();
return (arg) => {
if (!cache.has(arg)) {
cache.set(arg, fn(arg));
}
return cache.get(arg);
};
}
The cache lives in the closure returned by memoize, so it survives between
calls. has is checked before get, so a stored undefined still counts as a
cache hit. A repeated argument returns the same value and never re-runs fn.
A new argument misses the cache, runs fn once, and is stored for next time.
Export memoize from index.js. Your job is to make it cache the result for
each argument instead of recomputing.
Challenge
Call an expensive function twice with the same argument and it does all the work
twice, even though the answer cannot have changed. Export a memoize function
from index.js to remember each result.
memoize takes a function and returns a new function that caches results by
argument: the first call with a given argument runs the original and stores the
result, and every later call with the same argument returns the stored result
without running it again. A different argument still runs the original once.