Skip to the solution
MediumFrontend6 min read

Implement memoize() with custom resolver and cache limit

607 views

The problem

Problem, as an interviewer would state it: "Implement memoize(fn, options) — cache the result of a call so repeated calls with the same arguments skip real recomputation. Support a custom resolver function for computing the cache key, and a maxSize that evicts the oldest entry once exceeded."

Examples:

Code
const memoSquare = memoize(expensiveSquare);
memoSquare(5); // real computation
memoSquare(5); // cached, no real computation

Clarifying questions expected:

  • If no resolver is given, how should the default cache key be computed for multiple arguments?
  • On maxSize eviction, is it always the LEAST RECENTLY USED entry that goes, or strictly the oldest by insertion?
  • Should accessing a cached entry refresh its recency for eviction purposes?

Code / implementation expected: Yes — real, direct proof of plain caching, a custom resolver ignoring an argument, and maxSize eviction genuinely forcing a real recomputation.

  • memoize
  • cache
  • closure

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: memoize() caches correctly, a custom resolver correctly ignores an unconsidered argument, and maxSize eviction forces a real recomputation

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 108 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Deep Freeze Object

Continue