Skip to main content

Search

Search problems, hooks, and pages

Memoize a Function

Implement memoize(fn) that caches results by arguments, so repeated calls with the same inputs return the cached value instead of recomputing. This is a closures + caching classic — interviewers often follow up with custom key resolvers and cache invalidation.

Examples

Input: const f = memoize(square); f(4); f(4);
Output: 16, 16 — but square runs only once
// The second call with the same argument returns the cached result.
Input: memoize(fib) for fib(40)
Output: 102334155, computed quickly
// Memoising the recursive calls turns exponential work into linear.

Constraints

  • Repeated calls with equal arguments must not recompute.
  • Preserve the original this context and forward all arguments.
  • Bonus: allow a custom key resolver and a way to clear the cache.
closurecachehigher-order-functionperformanceMap

Important

Interview Tip

Use a Map for the cache. The naive JSON.stringify key is fine to mention but call out its limits (functions/undefined dropped, key-order sensitivity, cost for large args). Offer a custom resolver as the production answer, and mention WeakMap when keys are objects you want garbage-collected.

Approach: JSON Key Cache

Serialise the arguments with JSON.stringify to form a cache key, store results in a Map. The quick standard answer.

Complexity

Time: O(1) lookupSpace: O(n) cache

Pros

  • Handles multiple arguments
  • Simple to write
  • Map avoids prototype pitfalls

Cons

  • JSON.stringify is lossy and slow
  • Key-order sensitive
  • Cannot key on functions