Javascript Fundamentals ยท Interview Challenges

Memoize a function

memoize

Memoize a function

You call an expensive fibonacci(30) and wait. A moment later you need it again and wait the same amount, even though nothing about the argument changed. The same work is being thrown away and redone.

The fix is to remember what a call returned. The first call with a given argument runs the function and stores the result; every later call with the same argument returns the stored result. That pattern is called memoize: a cache keyed by argument.

The shape keeps a cache in a closure. On each call, check whether the argument is already a key; if not, compute and store it:

function memoize(fn) {
  const cache = new Map();
  return (arg) => {
    if (!cache.has(arg)) {
      cache.set(arg, fn(arg));
    }
    return cache.get(arg);
  };
}

The cache lives in the closure returned by memoize, so it survives between calls. has is checked before get, so a stored undefined still counts as a cache hit. A repeated argument returns the same value and never re-runs fn. A new argument misses the cache, runs fn once, and is stored for next time.

Export memoize from index.js. Your job is to make it cache the result for each argument instead of recomputing.

Challenge

Call an expensive function twice with the same argument and it does all the work twice, even though the answer cannot have changed. Export a memoize function from index.js to remember each result.

memoize takes a function and returns a new function that caches results by argument: the first call with a given argument runs the original and stores the result, and every later call with the same argument returns the stored result without running it again. A different argument still runs the original once.

index.js
export function memoize(fn) {
  return (arg) => fn(arg);
}

export function render(mount) {
  let calls = 0;
  const double = memoize((value) => {
    calls += 1;
    return value * 2;
  });

  const first = double(21);
  const second = double(21);

  const results = document.createElement('p');
  results.textContent = `double(21) = ${first}, then ${second}`;
  const callCount = document.createElement('p');
  callCount.textContent = `Calls: ${calls}`;
  mount.append(results, callCount);
}

No test run yet

The Test is hidden. Run it to check the Challenge โ€” you only see the result, never the test source.