Create an LRU Cache (Bounded Memory)
Arguments
maxSize: number —Maximum number of entries to retain. Must be a positive integer.
Returns
{ get, set, has, size, clear, keys } — 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.
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'); // => falseSolution
Overview
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.
Approach: Map insertion-order (recommended)
Rules:
- get(key): if present, move to most-recent (delete + set).
- set(key, value): write, then evict oldest if size > maxSize.
Complexity:
- get/set/has: O(1) average
- keys(): O(n)
export default function createLruCache(maxSize) {
if (!Number.isFinite(maxSize) || maxSize % 1 !== 0 || maxSize <= 0) {
throw new TypeError('maxSize must be a positive integer');
}
const map = new Map();
const touch = (key, value) => {
map.delete(key);
map.set(key, value);
};
const evictIfNeeded = () => {
while (map.size > maxSize) {
const oldest = map.keys().next().value;
map.delete(oldest);
}
};
return {
get(key) {
if (!map.has(key)) return undefined;
const value = map.get(key);
touch(key, value);
return value;
},
set(key, value) {
touch(key, value);
evictIfNeeded();
},
has(key) {
return map.has(key);
},
size() {
return map.size;
},
clear() {
map.clear();
},
keys() {
return Array.from(map.keys());
}
};
}
export type LruCache<K, V> = {
get: (key: K) => V | undefined;
set: (key: K, value: V) => void;
has: (key: K) => boolean;
size: () => number;
clear: () => void;
keys: () => K[];
};
export default function createLruCache<K, V>(maxSize: number): LruCache<K, V> {
if (!Number.isFinite(maxSize) || maxSize % 1 !== 0 || maxSize <= 0) {
throw new TypeError('maxSize must be a positive integer');
}
const map = new Map<K, V>();
const touch = (key: K, value: V) => {
map.delete(key);
map.set(key, value);
};
const evictIfNeeded = () => {
while (map.size > maxSize) {
const oldest = map.keys().next().value as K;
map.delete(oldest);
}
};
return {
get(key: K) {
if (!map.has(key)) return undefined;
const value = map.get(key) as V;
touch(key, value);
return value;
},
set(key: K, value: V) {
touch(key, value);
evictIfNeeded();
},
has(key: K) {
return map.has(key);
},
size() {
return map.size;
},
clear() {
map.clear();
},
keys() {
return Array.from(map.keys());
}
};
}
Notes & Pitfalls
Unbounded caches become real memory problems in long-lived tabs. A cache key strategy matters: if you key by URL with tracking params, you will explode cardinality. LRU helps memory, but eviction can hurt hit-rate; choose maxSize based on real usage. Updating an existing key in place without moving it: it stays the oldest entry and is the next one evicted. Evicting before inserting: updating a key at capacity would drop another entry, although the size does not grow.
maxSize must be > 0; throw for invalid inputs. Updating an existing key should refresh recency without growing size. get() should also refresh recency.
Map insertion order as an LRU list. delete+set to move key to most recent. Evict oldest via map.keys().next().value.
Common mistakes on this challenge
Treat an update as a use, and evict only when the size grows
The checks update a key and then add another one, expecting the updated key to stay, and update a key at capacity, expecting nothing to be evicted. In set, delete the key before setting it again, so theMapmoves it to the most recent end.Evict after the write, and only while map.size > maxSize; updating a stored key does not grow the size.keys()lists keys from least to most recently used, andsize()is a method.
LRU recency updates or eviction order is incorrect
Map insertion order must be maintained carefully on both get and set. Validate maxSizeas a positive integer before creating cache.On get, refresh recency via delete+set before returning value.On set, touch key then evict the oldest key while size exceeds limit.
Resources
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.