← All Exercises

Byte-Budgeted localStorage LRU Eviction

advancedjavascript~15min

Background

Browser storage quotas are small and shared across a site. Production caches combine an LRU policy with byte accounting so a single oversized value cannot evict everything else.

Problem

Implement runCache(budget, ops) for a localStorage-like store. Each entry costs key.length + value.length, sets update recency, gets promote an entry, and when a write exceeds the budget the least recently used keys are evicted. A single entry larger than the whole budget is rejected without changing state.

Input

A JSON object with budget and ops, where each op is a set (key, value) or a get (key).

Output

A JSON object with keys in LRU-to-MRU order, evicted keys in eviction order, hits, and misses.

Sample tests

Sample 1

Input: {"budget":5,"ops":[{"type":"set","key":"a","value":"1"},{"type":"set","key":"b","value":"2"},{"type":"get","key":"a"},{"type":"set","key":"c","value":"3"},{"type":"get","key":"b"}]}
Expected: {"keys":["a","c"],"evicted":["b"],"hits":1,"misses":1}

Sample 2

Input: {"budget":5,"ops":[{"type":"set","key":"a","value":"1"},{"type":"set","key":"b","value":"2"},{"type":"set","key":"a","value":"123"}]}
Expected: {"keys":["a"],"evicted":["b"],"hits":0,"misses":0}

Sample 3

Input: {"budget":3,"ops":[{"type":"set","key":"a","value":"1"},{"type":"set","key":"huge","value":"xx"}]}
Expected: {"keys":["a"],"evicted":[],"hits":0,"misses":0}

Your solution

Learning objective

Understand LRU ordering with Map, byte accounting, and eviction policies for client-side storage.