CS Fundamentals Trainer · JavaScript · Performance & Memory
Predict the output: a size-bounded LRU cache built on Map.
Predict the output: a size-bounded LRU cache built on `Map`.
class LruCache {
constructor(limit) { this.limit = limit; this.map = new Map(); }
get(key) {
if (!this.map.has(key)) return undefined;
const value = this.map.get(key);
this.map.delete(key);
this.map.set(key, value);
return value;
}
set(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);
}
}
const cache = new LruCache(2);
cache.set('a', 1); cache.set('b', 2);
cache.get('a');
cache.set('c', 3);
console.log([...cache.map.keys()], cache.get('b'));
Difficulty: medium