Skip to curriculum
Jump to the editor

20.3. An LRU cache

Medium
Topics

This question is in

20. Caches and buffers
20–35 min

Memory 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

JAVASCRIPT
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

  1. capacity must be a positive integer (RangeError otherwise); onEvict, when given, must be a function (TypeError otherwise).
  2. set stores the value and returns the cache; get returns it, or undefined for a missing key (a miss changes nothing).
  3. Only get and set count as use. has and peek never change which entry is evicted next.
  4. When a set of a new key makes the size exceed capacity, the least recently used entry is removed. The size never exceeds capacity.
  5. Setting an existing key updates its value and makes it the most recently used; it never evicts.
  6. onEvict(key, value) is called once for each evicted entry, after it has been removed. delete, overwriting and clear are not evictions.
  7. delete returns whether the key was there; it frees a place, so the next new key evicts nothing.
  8. keys() returns the keys from least to most recently used.
  9. An entry whose value is undefined is an entry like any other, and get on it still counts as use.
  10. Keys can be any value and are compared like Map keys.
  11. get and set take constant time: 200,000 operations on a cache of 20,000 entries finish well within the time limit.

Examples

JAVASCRIPT
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"]
JAVASCRIPT
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 evicted
JAVASCRIPT
new LRUCache(0);        // RangeError
new LRUCache(1).get("x"); // undefined

Environment

  • Plain JavaScript in a browser page; the tests create new LRUCache(…) from lru-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

  1. A Map remembers the order in which keys were inserted. How can you make a key count as "inserted just now"?
  2. Which entry of a Map is 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…