LRU Cache With Map Insertion Order

Implement an LRU cache using Map insertion order for O(1) get set and eviction with optional TTL expiry.

JavascriptData Fetching

Code

javascriptsnippet
1 line
export class LRUCache{constructor({maxSize=100,ttl=Infinity}={}){this.maxSize=maxSize;this.ttl=ttl;this.cache=new Map();}get(key){if(!this.cache.has(key))return undefined;const{value,time}=this.cache.get(key);if(Date.now()-time>=this.ttl){this.cache.delete(key);return undefined;}this.cache.delete(key);this.cache.set(key,{value,time});return value;}set(key,value){if(this.cache.has(key))this.cache.delete(key);this.cache.set(key,{value,time:Date.now()});if(this.cache.size>this.maxSize)this.cache.delete(this.cache.keys().next().value);}has(key){return this.get(key)!==undefined;}clear(){this.cache.clear();}get size(){return this.cache.size;}}

How it works

Count the class LRUCache as the entire surface area of LRU Cache With Map Insertion Order.

Putting it to use

The surface worth importing is LRUCache; the helpers around it are private to the snippet.

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API.