LRU Cache With Map Ordering
Implement a least-recently-used cache that evicts the oldest entry when capacity is exceeded, reusing Map insertion order to track recency.
Code
export class LruCache {
constructor(capacity) {
if (capacity <= 0) throw new RangeError("capacity must be positive");
this.capacity = capacity;
this.entries = new Map();
}
get(key) {
if (!this.entries.has(key)) return undefined;
const value = this.entries.get(key);
this.entries.delete(key);
this.entries.set(key, value);
return value;
}
set(key, value) {
if (this.entries.has(key)) this.entries.delete(key);
this.entries.set(key, value);
if (this.entries.size > this.capacity) {
const oldest = this.entries.keys().next().value;
this.entries.delete(oldest);
}
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.