Memoize

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 getCallCount(), reporting how many times the original actually ran.

Examples

Example 1
Input
const sum = memoize((a, b) => a + b);
sum(2, 2);  // 4, computed
sum(2, 2);  // 4, from cache
sum.getCallCount();
Output
1
Explanation
The second call was served from the cache, so the original ran once.

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.
  • The harder version (LeetCode 2630) keys on argument identity, which rules out JSON.stringify entirely.

Hints

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