Memoize LRU Cache With TTL Eviction
Create a memoizing wrapper with LRU cache bounded by max size and per-entry TTL eviction for caching expensive pure functions.
Code
export function memoizeLRU(fn,{maxSize=100,ttl=Infinity}={}){const cache=new Map();function m(...a){const key=JSON.stringify(a);if(cache.has(key)){const e=cache.get(key);if(Date.now()-e.time<ttl){cache.delete(key);cache.set(key,e);return e.value;}cache.delete(key);}const v=fn.apply(this,a);cache.set(key,{value:v,time:Date.now()});if(cache.size>maxSize)cache.delete(cache.keys().next().value);return v;}m.cache=cache;return m;}How the snippet works
Memoize LRU Cache With TTL Eviction comes down to the functions memoizeLRU and m.
Applying it
The primary signature is export function memoizeLRU(fn,{maxSize=100,ttl=Infinity}={})
Import memoizeLRU from the file and call it — the rest of the code is implementation detail.
Interactive Tools for This Topic
Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. The file defines `memoizeLRU`, `m` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.