Implement a typed least-recently-used cache
TypeScript
// Generic LRU cache backed by Map insertion order.
class LruCache<K, V> {
private readonly store = new Map<K, V>();
constructor(private readonly capacity: number) {
if (!Number.isInteger(capacity) || capacity < 1) throw new RangeError('invalid capacity');
}
get(key: K): V | undefined {
if (!this.store.has(key)) return undefined;
const value = this.store.get(key) as V;
this.store.delete(key);
this.store.set(key, value); // refresh recency
return value;
}
set(key: K, value: V): void {
if (this.store.has(key)) this.store.delete(key);
this.store.set(key, value);
while (this.store.size > this.capacity) {
const oldest = this.store.keys().next();
if (oldest.done) break;
this.store.delete(oldest.value);
}
}
get size(): number {
return this.store.size;
}
}
const cache = new LruCache<string, number>(2);
cache.set('a', 1);
cache.set('b', 2);
cache.get('a'); // 'a' is now the most recent
cache.set('c', 3); // evicts 'b'
console.log(cache.get('b'), cache.get('a'), cache.get('c'), cache.size);
// undefined 1 3 2