FrontendPro

31Implement memoize() with custom cache keys

mediumAbout 35 minutesCodingcachingclosuresperformance

Problem

Implement memoize(fn, resolver). It returns a function that caches the results of fn, so calling it again with the same key returns the cached result without calling fn.

The cache key is:

  • resolver(...args) when a resolver is given (called with the same this),
  • otherwise the argument itself when there is exactly one argument,
  • otherwise JSON.stringify(args).

The memoized function exposes its cache as memoized.cache (a Map), so callers can clear or inspect it.

const slowSquare = (n) => { /* expensive */ return n * n; };
const square = memoize(slowSquare);
square(9); // computed
square(9); // from the cache

const getUser = memoize(fetchUserProfile, (user) => user.id);
getUser({ id: 1, name: "A" });
getUser({ id: 1, name: "A (new object)" }); // cache hit: same id

Requirements

  • Cache results that are undefined, null, 0 or false too.
  • Objects passed as the only argument are compared by reference by default.
  • Forward this to both fn and resolver.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Video walkthroughs

Stuck? Watch someone solve it, then try again on your own.

Memoize - Leetcode 2623 - JavaScript 30-Day ChallengeNeetCodeIO on YouTubeOpen on YouTube
Memoization: From Simple to ComplexNeciu Dan - The Señor Developer on YouTubeOpen on YouTube

Step-by-step

Use resolver.apply(this, args) when there is a resolver. Without one, a single argument is its own key, which works for objects because Map keys can be objects. Several arguments are combined with JSON.stringify(args).

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 5 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever