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

264 views

4

class LRUCache {
    constructor(capacity) {
        this.capacity = capacity;
        this.data = new Map();
    }
    get(key) {
        if (!this.data.has(key)) return undefined;
        const value = this.data.get(key);
        this.data.delete(key);
        this.data.set(key, value);
        return value;
    }
    put(key, value) {
        if (this.data.has(key)) this.data.delete(key);
        this.data.set(key, value);
        if (this.data.size > this.capacity) {
            const oldestKey = this.data.keys().next().value;
            this.data.delete(oldestKey);
        }
    }
    get size() { return this.data.size; }
}

const cache = new LRUCache(2);
cache.put('a', 1);
cache.put('b', 2);
cache.get('a');
cache.put('c', 3);           // should evict 'b' (least recently used)
console.log(cache.get('a')); // 1
console.log(cache.get('b')); // undefined
console.log(cache.get('c')); // 3

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.