Implement memoize
Write memoize(fn, resolver) that returns a version of fn which caches its results. By default the cache key is the first argument. If a resolver function is passed, the key is resolver(...args) instead.
const square = memoize((n) => n * n): the firstsquare(4)computes16, the nextsquare(4)returns it without callingfnconst m = memoize((a, b) => a + b):m(1, 2)and thenm(1, 100)both return3(same first argument)memoize(add, (a, b) => a + ',' + b)caches(1, 2)and(1, 100)separately
Compare keys the way a Map does: 1 and '1' are different keys, and objects are matched by reference. Falsy results like 0 or undefined must be cached too, and fn should be called with the same this as the memoized function.
Define memoize in the editor. 8 tests will call it.
Hint 1Create a Map inside memoize. The returned function closes over it, so every call shares the same cache.
Hint 2Compute the key as resolver ? resolver(...args) : args[0], and use cache.has(key) (not the truthiness of the cached value) to decide whether to call fn.
Hint 3Return a regular function, not an arrow, and call fn.apply(this, args) so this is passed through.
one clean solution
function memoize(fn, resolver) {
const cache = new Map();
return function memoized(...args) {
const key = resolver ? resolver.apply(this, args) : args[0];
if (cache.has(key)) return cache.get(key);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}