Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
20.3. An LRU cache
Medium
Topics
This question is in
20. Caches and buffersMemory for a cache is limited: decoded images, rendered pages and API responses cannot all stay. When the cache is full, something must go, and a good guess is the entry nobody has used for the longest time. That rule is LRU, least recently used. It is the eviction rule of many image loaders, data-fetching libraries and in-memory server caches.
Write an LRUCache class in lru-cache.js. Reads and writes must take constant time, however large the cache is.
Signature
class LRUCache {
constructor(capacity, onEvict) // capacity: a positive integer; onEvict(key, value) optional
get size() // the number of entries
get(key) // the value, or undefined; counts as use
peek(key) // the value, or undefined; does not count as use
has(key) // true or false; does not count as use
set(key, value) // counts as use; may evict; returns the cache
delete(key) // true if it was there
keys() // the keys, least recently used first
clear() // removes everything
}Requirements
capacitymust be a positive integer (RangeErrorotherwise);onEvict, when given, must be a function (TypeErrorotherwise).setstores the value and returns the cache;getreturns it, orundefinedfor a missing key (a miss changes nothing).- Only
getandsetcount as use.hasandpeeknever change which entry is evicted next. - When a
setof a new key makes the size exceedcapacity, the least recently used entry is removed. The size never exceedscapacity. - Setting an existing key updates its value and makes it the most recently used; it never evicts.
onEvict(key, value)is called once for each evicted entry, after it has been removed.delete, overwriting andclearare not evictions.deletereturns whether the key was there; it frees a place, so the next new key evicts nothing.keys()returns the keys from least to most recently used.- An entry whose value is
undefinedis an entry like any other, andgeton it still counts as use. - Keys can be any value and are compared like
Mapkeys. getandsettake constant time: 200,000 operations on a cache of 20,000 entries finish well within the time limit.
Examples
const cache = new LRUCache(2, (key) => console.log("evicted", key));
cache.set("a", 1).set("b", 2);
cache.get("a"); // 1: now "b" is the least recently used
cache.set("c", 3); // logs "evicted b"
cache.keys(); // ["a", "c"]cache.peek("a"); // 1, and "a" is still least recently used
cache.set("d", 4); // logs "evicted a"
cache.set("d", 40); // an update: nothing is evictednew LRUCache(0); // RangeError
new LRUCache(1).get("x"); // undefinedEnvironment
- Plain JavaScript in a browser page; the tests create
new LRUCache(…)fromlru-cache.js. - Any built-in is allowed. One test runs 200,000 operations, so a linear search per call fails on time.
- Out of scope: expiry by time (problem 20.2), sizes per entry, and evicting by frequency (problem 20.4).
Hints
- A
Mapremembers the order in which keys were inserted. How can you make a key count as "inserted just now"? - Which entry of a
Mapis cheapest to find?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…