06 · Frontend Coding Patterns
easycodingjavascript~8 min

Implement memoize with a Key Resolver

Objective: Cache pure computations and choose cache keys deliberately.

Write `memoize(fn, resolver)`. Results are cached by the key the resolver returns (default: the first argument).

  • The wrapped function calls `fn` only on a cache miss.
  • Default key is the first argument.
  • A custom `resolver(...args)` defines the key.
  • Cached `undefined`/`falsy` results are still cache hits.
JavaScript

⌘/Ctrl + Enter to run tests · Esc then Tab leaves the editor

Output
> Nothing has run yet.
Interview follow-up questions
  • What goes wrong when the key is an object?
  • How would you bound the cache size?
  • Why is memoizing an impure function dangerous?