Event Emitter & LRU Cache — JavaScript interview guide
23 / 23Interview CodingMedium priorityMedium 30 min
Event Emitter & LRU Cache
Two classic "design a small class" questions: a pub/sub event emitter and a Least Recently Used cache.
See it run
Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.
LRU cache: a Map remembers order, the oldest gets evicted
Execution phaseStep 1/7
script.js
▶const cache = new LRU(2); // keeps 2 items23cache.put("a", 1);4cache.put("b", 2);5cache.get("a"); // "a" was just used6cache.put("c", 3); // full! who leaves?7console.log([...cache.map.keys()]);
Call Stack
last in, first outMemory / Scope
cache.map (oldest → newest)
| keys | [ ] |
| limit | 2 |
Console
nothing printed yet
What happens:An LRU (Least Recently Used) cache with room for 2 items. Inside, it is just a Map — and a Map remembers insertion order.
Tip: click the box and use ← → keys to step, space to play.
Explained simply
Event emitter
Store listeners per event name; on returns an unsubscribe function.
class Emitter {
#events = new Map();
on(name, fn) {
if (!this.#events.has(name)) this.#events.set(name, new Set());
this.#events.get(name).add(fn);
return () => this.#events.get(name)?.delete(fn);
}
emit(name, ...args) {
this.#events.get(name)?.forEach((fn) => fn(...args));
}
}LRU cache with Map
A Map keeps insertion order, so the first key is the least recently used.
class LRU {
constructor(limit) { this.limit = limit; this.map = new Map(); }
get(key) {
if (!this.map.has(key)) return -1;
const v = this.map.get(key);
this.map.delete(key);
this.map.set(key, v); // move to newest
return v;
}
put(key, value) {
this.map.delete(key);
this.map.set(key, value);
if (this.map.size > this.limit) this.map.delete(this.map.keys().next().value);
}
}Remember this
- Return an unsubscribe function from on().
- Map gives O(1) get/put for LRU.
Interview questions
Why is Map a good fit for an LRU cache?
It preserves insertion order and supports O(1) get, set and delete, so re-inserting a key moves it to the newest position.
Practice
- Add once(name, fn) to the emitter.
Keep learning
More in Interview Coding