Implement memoize(fn, resolver?). It returns a new function that remembers results, so fn runs only once for each cache key.
- Cache key: if
resolveris given, the key isresolver(...args). Otherwise the key is the first argument only. - Keys are compared the way
Mapcompares keys. Primitives, such as numbers and strings, match by value. Objects match by reference, so two different objects with the same contents are different keys. - On a repeat key, return the stored result without calling
fn. This also applies when the stored result is a falsy value, such as0orundefined. fnruns with the samethisthe new function was called with.
Input: const sq = memoize(n => n * n);
sq(4); sq(4);
Output: 16, 16 (fn ran once)
Input: const add = memoize((a, b) => a + b);
add(1, 2); add(1, 100);
Output: 3, then 3Without a resolver, only the first argument is the key. So the second call finds its key in the cache.
Input: const add = memoize((a, b) => a + b, (a, b) => a + ',' + b);
add(1, 2); add(1, 100);
Output: 3, then 101