Cache With Time Limit
A key/value cache where every entry expires on its own timer — and setting a key again restarts its clock.
JavaScript · ES6 — Pratik Rai ·
A fixed-size cache that evicts whatever was used least recently — and does both reads and writes in constant time.
Build an LRUCache class that holds a fixed number of entries and, once full, throws away whichever entry was used least recently.
new LRUCache(capacity) — how many entries fit before eviction starts.get(key) — returns the value, or -1 if the key is not there. A successful get counts as a use.put(key, value) — inserts or updates. Counts as a use either way. If this takes the cache past its capacity, evict the least recently used entry.Both get and put must run in O(1) — no scanning the keys to find the oldest one.
Input:
JSfile.javascript1const cache = new LRUCache(3); 2 3cache.put('user:1', { name: 'Pratik' }); 4cache.put('user:2', { name: 'Rahul' }); 5cache.put('user:3', { name: 'Aman' }); 6 7cache.get('user:1'); // { name: 'Pratik' } 8 9cache.put('user:4', { name: 'Vikas' }); // over capacity 10 11cache.get('user:2'); 12cache.get('user:1');
Output:
-1
{ name: 'Pratik' }
Reading user:1 made it recently used, so when user:4 arrived the least recently used entry was user:2 — and that is the one evicted.
Goal: Evict the least recently used entry when full, with O(1) reads and writes.
Continue learning with these related challenges
A key/value cache where every entry expires on its own timer — and setting a key again restarts its clock.
JavaScript · ES6 — Pratik Rai ·
Run a list of async tasks with a hard limit on how many are in flight at once — the concurrency control Promise.all does not give you.
JavaScript · ES6 — Pratik Rai ·
Wrap an async function so it gives up after a deadline — the building block behind every request timeout.
JavaScript · ES6 — Pratik Rai ·
A key/value cache where every entry expires on its own timer — and setting a key again restarts its clock.
JavaScript · ES6
Pratik Rai ·
Run a list of async tasks with a hard limit on how many are in flight at once — the concurrency control Promise.all does not give you.
JavaScript · ES6
Pratik Rai ·
Wrap an async function so it gives up after a deadline — the building block behind every request timeout.
JavaScript · ES6
Pratik Rai ·