Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Implement memoize()

A Closer Look at Functionshard

Implement `memoize(fn)` that returns a function caching results by argument list, so the underlying `fn` runs at most once per distinct set of arguments. Repeated calls with the same arguments return the cached value without re-invoking `fn`.

Examples

Input: let calls = 0; const slow = (n) => { calls++; return n * 2; }; const m = memoize(slow); m(5); m(5); m(6); calls
Output: 2
m(5) runs once, the second m(5) is cached, m(6) runs once — 2 calls total.

Sample tests

Input: counts underlying calls
Output: 2
Input: returns the computed value
Output: 16

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Using only the first argument as the key gives wrong results for multi-argument functions.
  • Caching by reference identity misses equal-but-distinct argument arrays.

Learning resources

  • MDN: Closures
  • MDN: Functions guide
Approach & explanation (try first)

A closure holds a Map keyed by a serialized form of the arguments. On a cache hit the stored value is returned immediately; on a miss the function runs once and its result is recorded. This trades memory for speed on pure, repeatedly-called functions.

Loading...
⌘/Ctrl + Enter

Run your code to see results.