Memoize a Function

ClosuresHigher-Order FunctionsPerformance

Write memoize(fn) returning a function that behaves identically but never recomputes for arguments it has already seen.

The returned function also exposes callCount(), reporting how many times the original actually ran.

Examples

Example 1
Input
const greet = memoize((name, mark) => 'Hi ' + name + mark);
greet('Ada', '!');  // "Hi Ada!", computed
greet('Ada', '?');  // "Hi Ada?", computed
greet('Ada', '!');  // "Hi Ada!", from cache
greet.callCount();
Output
2
Explanation
The second call differs in one argument, so it is a new entry. The third repeats the first exactly and is served from the cache, so the original ran twice.

Constraints

  • Arguments are JSON-serialisable

Notes

  • A cached `0`, `false` or `undefined` is still a cached value — check whether the key exists, not whether the value is truthy.
  • A stricter version keys on argument identity rather than on a string, which rules out JSON.stringify entirely.

Hints

Read the full write-up for Memoize a Function
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it