Sikau

Data structures · Day 8 · about 45 min

Project: LRU cache

A fixed-size cache that evicts the least recently used item in O(1).

Remember what's hot

The menu API is slow, so cache recent answers — but memory is limited. An LRU cache keeps the most recently used entries and evicts the one untouched the longest. Browsers, CDNs and databases all use it.

Map remembers order

JavaScript's Map iterates keys in insertion order, which gives a very short LRU cache. To mark a key as recently used, delete it and set it again: it moves to the end. The least recently used key is then always the first one, available as map.keys().next().value. Every operation is O(1).

const m = new Map([["a", 1], ["b", 2], ["c", 3]]);
const v = m.get("a");
m.delete("a");
m.set("a", v);
console.log([...m.keys()]);
console.log(m.keys().next().value);

The rest of this lesson

  • get and set, preciselyexplain
  • The classic versionexplain
  • Who gets evicted?predict
  • Operation to effectmatch
  • LRUCachechallenge
  • Badge quizquiz
  • Unit 2 complete!recap

Continue this lesson free — run real code in your browser

Continue with Google

See all 13 lessons of Data structures