JavaScript › Map, Set, WeakMap & WeakSet
How would you use a Map to implement an LRU (Least Recently Used) cache?
AdvancedAnswer
A Map's guaranteed insertion order lets you track recency: on each access, delete and re-insert the key to move it to the 'most recent' end; when the cache exceeds its size limit, delete the first (oldest) key, obtained via map.keys().next().value.
class LRUCache {
#cache = new Map();
#limit;
constructor(limit) { this.#limit = limit; }
get(key) {
if (!this.#cache.has(key)) return undefined;
const value = this.#cache.get(key);
this.#cache.delete(key);
this.#cache.set(key, value); // move to most-recent
return value;
}
set(key, value) {
if (this.#cache.has(key)) this.#cache.delete(key);
else if (this.#cache.size >= this.#limit) {
this.#cache.delete(this.#cache.keys().next().value); // evict oldest
}
this.#cache.set(key, value);
}
}Real-world example Caching a limited number of recently fetched API responses in a browser app to reduce redundant network calls.