Closed aolagers closed 2 months ago
Simple LRU cache:
class LRUCache<K, V> { private capacity: number; private cache: Map<K, V>; constructor(capacity: number) { this.capacity = capacity; this.cache = new Map<K, V>(); } get(key: K): V | undefined { if (!this.cache.has(key)) { return undefined; } // Remove and re-insert to move to front (most recently used) const value = this.cache.get(key)!; this.cache.delete(key); this.cache.set(key, value); return value; } put(key: K, value: V): void { if (this.cache.has(key)) { // Remove existing entry this.cache.delete(key); } else if (this.cache.size >= this.capacity) { // Remove least recently used item (first item in Map) const leastUsedKey = this.cache.keys().next().value; this.cache.delete(leastUsedKey); } // Add new entry (automatically becomes most recently used) this.cache.set(key, value); } }
Simple LRU cache: