31Implement memoize() with custom cache keys
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 aresolveris given (called with the samethis),- 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 idRequirements
- Cache results that are
undefined,null,0orfalsetoo. - Objects passed as the only argument are compared by reference by default.
- Forward
thisto bothfnandresolver.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
Press Run or ⌘ Enter to execute your code.
Video walkthroughs
Stuck? Watch someone solve it, then try again on your own.
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.