1 class LRUCache {
2 constructor(capacity) {
3 this.cap = capacity;
4 this.map = new Map(); // key → node
5 this.head = new Node(); // MRU sentinel
6 this.tail = new Node(); // LRU sentinel
7 this.head.next = this.tail;
8 this.tail.prev = this.head;
9 }
11 get(key) {
12 if (!this.map.has(key)) return -1;
13 const node = this.map.get(key);
14 this._moveToFront(node);
15 return node.val;
16 }
18 put(key, value) {
19 if (this.map.has(key)) {
20 const node = this.map.get(key);
21 node.val = value;
22 this._moveToFront(node);
23 return;
24 }
25 if (this.map.size >= this.cap) {
26 const lru = this.tail.prev;
27 this._remove(lru);
28 this.map.delete(lru.key);
29 }
30 const node = new Node(key, value);
31 this.map.set(key, node);
32 this._addFront(node);
33 }
34 }