boundedLruCacheWithMapRecency
JavaScript
// Fixed-capacity LRU cache; Map insertion order is the recency order.
export class LruCache {
#maxSize;
#items = new Map();
constructor(maxSize) {
if (!Number.isInteger(maxSize) || maxSize < 1) {
throw new RangeError('maxSize must be a positive integer');
}
this.#maxSize = maxSize;
}
get(key) {
if (!this.#items.has(key)) return undefined;
const value = this.#items.get(key);
this.#items.delete(key);
this.#items.set(key, value); // move the hit to the most-recent position
return value;
}
set(key, value) {
this.#items.delete(key);
this.#items.set(key, value);
if (this.#items.size > this.#maxSize) {
this.#items.delete(this.#items.keys().next().value);
}
return this;
}
get size() {
return this.#items.size;
}
}