call(back)
FrontendmediumSign in to star problems

Implement memoize

Write memoize(fn, resolver): return a function that caches fn's result per key.

  • The key is resolver(...args), and by default JSON.stringify(args), so all arguments count.
  • A cached result is reused even when it is 0 or undefined.
  • The wrapper forwards this, and each memoized function has its own cache.
const add = memoize((a, b) => a + b);
add(1, 2); add(1, 2);   // fn runs once
add(2, 1);              // a different key: fn runs again

Hints

Hint 1

memoize closes over a Map. Test membership with cache.has(key), not a truthy lookup, so cached 0 and undefined results count as hits.

Hint 2

Return a function, not an arrow, and call fn.apply(this, args) so a memoized method still sees its object.

Asked at