Create an LRU Cache (Bounded Memory)

hard
By FrontendAtlas Editorial · Updated Nov 12, 2026
Implement createLruCache(maxSize) to keep a bounded, eviction-based cache. This is a classic way to prevent "memory leaks" caused by unbounded Maps in long-lived SPAs (analytics, image metadata, computed results).

Arguments

  • maxSize: number — Maximum number of entries to retain. Must be a positive integer.

Returns

{ get, set, has, size, clear, keys } — An object with get(key), set(key, value), has(key), size(), clear() and keys(). size() is a method that returns the number of entries, and keys() returns an array of the keys from least to most recently used. get and set make a key the most recent; has does not.

Solution idea

In JavaScript, Map preserves insertion order. You can implement LRU by moving a key to the end on get/set, and evicting the first key when size exceeds maxSize.

Examples
const c = createLruCache(2);
c.set('a', 1);
c.set('b', 2);
c.get('a'); // => 1 (a becomes most-recent)
c.set('c', 3); // evicts b
c.has('b'); // => false