LRU Cache TTL Generic Typed
Implement a generic typed LRU cache with TTL eviction and size bound using Map insertion order.
Code
export class LRUCache<K,V>{private cache=new Map<K,{value:V;expiry:number}>();constructor(private maxSize:number,private ttl:number){}get(key:K):V|undefined{const entry=this.cache.get(key);if(!entry)return undefined;if(Date.now()>entry.expiry){this.cache.delete(key);return undefined;}this.cache.delete(key);this.cache.set(key,entry);return entry.value;}set(key:K,value:V):void{if(this.cache.has(key))this.cache.delete(key);this.cache.set(key,{value,expiry:Date.now()+this.ttl});if(this.cache.size>this.maxSize)this.cache.delete(this.cache.keys().next().value!);}clear(){this.cache.clear();}get size(){return this.cache.size;}}What the code does
Count the class LRUCache as the entire surface area of LRU Cache TTL Generic Typed.
Points of care
- The guard
!entryshort-circuits the flow with an earlyreturnwhen its condition holds.
Using it
LRUCache is what another module would consume; nothing else here is load-bearing for callers.
Interactive Tools for This Topic
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring.
Report a problem with this exampleOpens a pre-filled issue on GitHub.