-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru.ts
86 lines (71 loc) · 1.52 KB
/
lru.ts
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
interface Node<T, U> {
key: U
value: T
prev?: Node<T, U>
next?: Node<T, U>
}
export class LRUCache<T, U = string> {
capacity: number
cache: Map<U, Node<T, U>> = new Map()
head?: Node<T, U>
tail?: Node<T, U>
constructor(capacity: number) {
this.capacity = capacity
}
get(key: U) {
const node = this.cache.get(key)
if (node) {
this.moveToHead(node)
return node.value
}
}
set(key: U, value: T) {
if (this.cache.has(key)) {
const node = this.cache.get(key)!
node.value = value
this.moveToHead(node)
return
}
if (this.cache.size >= this.capacity) {
this.cache.delete(this.tail!.key)
if (this.tail!.prev) {
this.tail!.prev.next = undefined
}
this.tail = this.tail!.prev
}
const node: Node<T, U> = { key, value }
this.cache.set(key, node)
if (!this.head) {
this.head = this.tail = node
return
}
this.head.prev = node
node.next = this.head
this.head = node
}
moveToHead(node: Node<T, U>) {
if (this.head === node) {
return
}
if (this.tail === node) {
this.tail = node.prev
}
node.prev!.next = node.next
if (node.next) {
node.next.prev = node.prev
}
node.prev = undefined
node.next = this.head
this.head!.prev = node
this.head = node
}
toString() {
let ret = []
let current = this.head
while (current) {
ret.push(current.key)
current = current.next
}
return ret.join('\n')
}
}