-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path2048_cache.js
106 lines (91 loc) · 2.4 KB
/
2048_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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
const newNode = item => {
return {
item: item,
next: null,
prev: null
}
};
class Linked {
constructor() {
this.pivot = newNode(null);
this.pivot.next = this.pivot;
this.pivot.prev = this.pivot;
}
appendLast(node) {
const tail = this.pivot.prev;
// pivot <-> .... <-> ... <-> tail <-> node <-> pivot
tail.next = node;
node.prev = tail;
node.next = this.pivot;
this.pivot.prev = node;
// pivot <-> pivot case:
// pivot <-> node <-> pivot
}
head() {
const actualHead = this.pivot.next;
if (actualHead != this.pivot) {
return actualHead;
} else {
// so that pivot is never leaked outside.
return null;
}
}
tail() {
const actualTail = this.pivot.prev;
if (actualTail != this.pivot) {
return actualTail;
} else {
// so that pivot is not leaked outside.
return null;
}
}
detachNode(node) {
// prev <-> node <-> next
// prev <-> next
const prev = node.prev;
const next = node.next;
node.prev = null;
node.next = null;
prev.next = next;
next.prev = prev;
}
}
class LRUCache {
constructor(maxSize) {
this.maxSize = maxSize
this.lruList = new Linked();
this.internalMap = new Map()
}
has(key) {
return this.internalMap.has(key);
}
set(key, value) {
if (this.internalMap.has(key)) {
const currentNode = this.internalMap.get(key)
this.lruList.detachNode(currentNode)
} else {
if (this.internalMap.size >= this.maxSize) {
// Eviction Condition
const lruNode = this.lruList.head()
if (lruNode) {
this.lruList.detachNode(lruNode)
this.internalMap.delete(lruNode.item.key)
}
}
}
const toInsert = newNode({key, value});
this.lruList.appendLast(toInsert);
this.internalMap.set(key, toInsert)
}
size() {
return this.internalMap.size;
}
get(key) {
const currentNode = this.internalMap.get(key)
if (currentNode) {
return currentNode.item.value;
} else {
return null;
}
}
}