-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru-cache.js
92 lines (77 loc) · 1.54 KB
/
lru-cache.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
class ListNode {
next;
tail;
val;
key;
constructor(key, val) {
this.key = key;
this.val = val;
}
}
/**
* @param {number} capacity
*/
class LRUCache {
map;
capacity;
head;
tail;
size;
constructor(capacity) {
this.capacity = capacity;
this.size = 0;
this.map = {};
this.head = new ListNode(0, 0);
this.tail = new ListNode(0, 0);
this.head.next = this.tail;
this.tail.prev = this.head;
}
get(key) {
if (!this.map[key]) {
return -1;
}
const node = this.map[key];
this.moveToFront(node);
return node.val;
}
put(key, value) {
if (this.map[key]) {
const node = this.map[key];
node.val = value;
this.moveToFront(node);
} else {
if (this.atCapacity()) {
this.evict();
}
const newNode = new ListNode(key, value);
this.map[key] = newNode;
this.size++;
this.addToFront(newNode);
}
}
atCapacity() {
return this.size === this.capacity;
}
evict() {
const lastNode = this.tail.prev;
delete this.map[lastNode.key];
this.size--;
const prevNode = lastNode.prev;
this.tail.prev = prevNode;
prevNode.next = this.tail;
}
addToFront(node) {
const firstNode = this.head.next;
this.head.next = node;
node.prev = this.head;
node.next = firstNode;
firstNode.prev = node;
}
moveToFront(node) {
const prevNode = node.prev;
const nextNode = node.next;
prevNode.next = nextNode;
nextNode.prev = prevNode;
this.addToFront(node);
}
}