CodePark/ problems / memoize
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Closures and higher-order functions

memoize

mediumabout 20 minutes in an interview

Implement memoize(fn, resolver?). It returns a new function that remembers results, so fn runs only once for each cache key.

  • Cache key: if resolver is given, the key is resolver(...args). Otherwise the key is the first argument only.
  • Keys are compared the way Map compares 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 as 0 or undefined.
  • fn runs with the same this the 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