JavaScript Snippet

LRU Cache (Map-Backed)

Difficulty: Medium

An LRU (Least Recently Used) cache evicts the entry that has been untouched the longest when capacity overflows. The trick that makes both `get` and `put` O(1) is JavaScript's `Map` preserving insertion order. This snippet covers the Map-backed implementation, an explicit doubly-linked-list version that mirrors what other languages need, and a TTL-aware variant that evicts entries that are too old.

Code Snippets
/

LRU Cache (Map-Backed)

LRU Cache (Map-Backed)

An LRU (Least Recently Used) cache evicts the entry that has been untouched the longest when capacity overflows. The trick that makes both `get` and `put` O(1) is JavaScript's `Map` preserving insertion order. This snippet covers the Map-backed implementation, an explicit doubly-linked-list version that mirrors what other languages need, and a TTL-aware variant that evicts entries that are too old.

JavaScript
Medium
3 snippets
data-structures
lru-cache
code-template
hash-table

263 views

4

JavaScript's Map keeps keys in insertion order, and re-setting an existing key does NOT move it to the end (which means we have to delete and re-insert). On get, we delete-and-reinsert to mark the key as recently used. On put, we evict the oldest by reading data.keys().next().value. Both operations are O(1) on a Map, so the cache is O(1) for both get and put. This is the cleanest LRU implementation in modern JavaScript and the version most production code uses.