Tech Interview RoomStudy guides

Frontend Coding

Implement memoize and an LRU cache.

Intermediate · 2 min read · Lesson 8 of 10 in Frontend Coding

memoize

Cache a pure function's results by its arguments. Choices to discuss:

  • Cache key: the first argument for single-argument functions; JSON.stringify(args) or a custom resolver for several (careful with objects: equal content gives equal keys, but key order matters and it costs time).
  • Unbounded growth: a plain Map grows forever, which is a memory leak in long-lived apps. Bound it with an LRU or use a WeakMap when the key is an object.
  • Async functions: cache the promise so concurrent calls share one request, and delete the entry if it rejects so errors are not cached.

LRU (Least Recently Used) cache

Keeps the capacity most recently used entries. get and put should be O(1). In JavaScript a Map remembers insertion order, so: on get, delete and re-insert the key (now most recent); on put over capacity, evict map.keys().next().value (the oldest). The classic language-neutral answer is a hash map plus a doubly linked list.

js
class LRUCache {
  #map = new Map();
  constructor(capacity) { this.capacity = capacity; }

  get(key) {
    if (!this.#map.has(key)) return undefined;
    const value = this.#map.get(key);
    this.#map.delete(key);
    this.#map.set(key, value);                // now the most recently used
    return value;
  }

  set(key, value) {
    if (this.#map.has(key)) this.#map.delete(key);
    else if (this.#map.size >= this.capacity) this.#map.delete(this.#map.keys().next().value); // evict oldest
    this.#map.set(key, value);
    return this;
  }

  has(key) { return this.#map.has(key); }
  delete(key) { return this.#map.delete(key); }
  get size() { return this.#map.size; }
  keys() { return [...this.#map.keys()]; }
}

function memoize(fn, { resolver = (...args) => JSON.stringify(args), maxSize = 500 } = {}) {
  const cache = new LRUCache(maxSize);
  function memoized(...args) {
    const key = resolver(...args);
    if (cache.has(key)) return cache.get(key);
    const result = fn.apply(this, args);
    cache.set(key, result);
    if (result instanceof Promise) result.catch(() => cache.delete(key));  // don't cache failures
    return result;
  }
  memoized.cache = cache;
  return memoized;
}

// Demo
const lru = new LRUCache(2);
lru.set('a', 1).set('b', 2);
lru.get('a');                       // a becomes most recent
lru.set('c', 3);                    // evicts b
assert.deepEqual(lru.keys(), ['a', 'c']);
assert.equal(lru.get('b'), undefined);

let calls = 0;
const slowSquare = memoize(n => { calls++; return n * n; });
assert.equal(slowSquare(9), 81);
assert.equal(slowSquare(9), 81);
assert.equal(calls, 1);

let requests = 0;
const fetchUser = memoize(async id => { requests++; await new Promise(r => setTimeout(r, 10)); return { id }; });
const [u1, u2] = await Promise.all([fetchUser(7), fetchUser(7)]);   // concurrent calls share one promise
assert.equal(requests, 1);
assert.equal(u1, u2);
console.log('LRU keys:', lru.keys(), 'square calls:', calls, 'requests:', requests);

Example

Memoised recursion turns exponential Fibonacci into linear time, a common warm-up:

js
const fib = memoize(n => (n < 2 ? n : fib(n - 1) + fib(n - 2)), { resolver: n => n });
assert.equal(fib(50), 12586269025);

Without memoisation fib(50) makes over 40 billion calls; with it, 51.

Follow-up questions interviewers ask

Try answering each one before you open it.

How is this related to React's useMemo and TanStack Query?

useMemo is a cache of size one per component (it remembers only the last inputs). TanStack Query and SWR are async memoisation with keys, deduplication of in-flight requests, expiry (staleTime), garbage collection of unused entries and invalidation: the same ideas as above, built for server data.