JavaScriptFundamental (ES6), part 1
Build an LRU cache with a Map in JavaScript
105 an LRU cache built on Map insertion order
hardBuild a fixed-size cache that evicts the least recently used entry. Exploit the fact that a Map remembers insertion order: deleting a key and setting it again moves it to the newest end. Prove that a read counts as a use, that has does not, and that a cached undefined is indistinguishable from a miss.
Stuck? Three hints, smallest first
- 1. A
Mapiterates oldest-inserted first, somap.keys().next().valueis the entry to evict. - 2. To mark a key as freshly used,
deleteit andsetit again. There is no other way to move a key within a Map. - 3. Evict after inserting, not before: check
size > maxonce the new entry is in, so overwriting an existing key never evicts anything.
class LruCache {
#max;
#items = new Map();
constructor(max) {
if (!Number.isInteger(max) || max < 1) throw new RangeError('max must be a positive integer');
this.#max = max;
}
get(key) {
if (!this.#items.has(key)) return undefined;
const value = this.#items.get(key);
this.#items.delete(key); // a read is a use: move it to the newest end
this.#items.set(key, value);
return value;
}
set(key, value) {
if (this.#items.has(key)) this.#items.delete(key);
this.#items.set(key, value);
if (this.#items.size > this.#max) {
const oldest = this.#items.keys().next().value;
this.#items.delete(oldest);
}
return this;
}
has(key) {
return this.#items.has(key); // deliberately NOT a use
}
get size() {
return this.#items.size;
}
keys() {
return [...this.#items.keys()]; // oldest first
}
}
const quotes = new LruCache(3);
quotes.set('yaba-ikeja', 1500).set('lekki-vi', 2500).set('ojota-ikeja', 1800);
const orderBefore = quotes.keys();
const hit = quotes.get('yaba-ikeja');
const orderAfterRead = quotes.keys();
quotes.set('surulere-yaba', 900);
const orderAfterEvict = quotes.keys();
const evictedRead = quotes.get('lekki-vi') === undefined;
const sizeCapped = quotes.size;
quotes.set('ojota-ikeja', 2000);
const orderAfterUpdate = quotes.keys();
const sizeAfterUpdate = quotes.size;
const present = quotes.has('yaba-ikeja');
const orderAfterHas = quotes.keys();
quotes.set('kano-kaduna', undefined);
const holdsUndefined = [quotes.has('kano-kaduna'), quotes.get('kano-kaduna') === undefined, quotes.has('nowhere')];
const finalKeys = quotes.keys();
let badMax = 'no error';
try { new LruCache(0); } catch (e) { badMax = e.constructor.name; }
console.log('inserted :', orderBefore);
console.log('after read:', orderAfterRead, '| hit:', hit);
console.log('evicted :', orderAfterEvict, '| size:', sizeCapped);
console.log('final :', finalKeys, '| bad max:', badMax);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('keys come out oldest first, which is insertion order', orderBefore, ['yaba-ikeja', 'lekki-vi', 'ojota-ikeja']);
test('a read is a use, so the key it touched moves to the newest end', [hit, orderAfterRead], [1500, ['lekki-vi', 'ojota-ikeja', 'yaba-ikeja']]);
test('the next write evicts the oldest, which is now the one nobody read', [orderAfterEvict, evictedRead], [['ojota-ikeja', 'yaba-ikeja', 'surulere-yaba'], true]);
test('so the size never passes the limit', sizeCapped, 3);
test('overwriting an existing key refreshes it without growing anything', [orderAfterUpdate, sizeAfterUpdate], [['yaba-ikeja', 'surulere-yaba', 'ojota-ikeja'], 3]);
test('has answers without counting as a use, so the order is unchanged', [present, orderAfterHas], [true, ['yaba-ikeja', 'surulere-yaba', 'ojota-ikeja']]);
test('a cached undefined reads exactly like a miss, which is why has exists', holdsUndefined, [true, true, false]);
test('and the newest three are what is left, the first key having aged out', finalKeys, ['surulere-yaba', 'ojota-ikeja', 'kano-kaduna']);
test('a limit below one throws instead of building a cache that cannot hold anything', badMax, 'RangeError');
The trick is that Map guarantees insertion order for every key type, and there is no operation to move a key within it. So "mark as recently used" becomes delete-then-set, and "least recently used" becomes the first key the iterator hands you. That is a real LRU in about twenty lines, with every operation O(1), and no linked list to maintain — the Map already is one.
Two decisions to be deliberate about. Evicting after the insert, on size > max, is what makes overwriting an existing key harmless; check before, on size >= max, and updating a key you already hold throws away an unrelated entry. And has not counting as a use is a choice: it makes has safe for diagnostics and cache-inspection code, and it means a caller who checks has then calls get touches recency exactly once.
The undefined assertion is the one that bites. get returns undefined both for a miss and for a key genuinely holding undefined, so a cache used to memoise a function that can return undefined recomputes for ever unless the caller asks has first. The alternatives are to store a wrapper such as { value }, or to return a sentinel object for a miss. Map itself has the same shape of problem, which is why has exists there too.