coding round · ~12 min
JavaScriptintermediate

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 first square(4) computes 16, the next square(4) returns it without calling fn
  • const m = memoize((a, b) => a + b): m(1, 2) and then m(1, 100) both return 3 (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.

solution.js
function memoize(fn, resolver) {
  // Return a function that caches fn's results.
  // Cache key: resolver(...args) if a resolver is given, otherwise the first argument.
}

Tests⌘/Ctrl + Enter to run

returns the same results as the original function
calls the original only once per key
uses only the first argument as the default key
uses the resolver to build the cache key
caches falsy results like 0 and undefined
compares keys like a Map (1 vs '1', objects by reference)
calls the original with the same this
each memoized function has its own cache
esc