-
Notifications
You must be signed in to change notification settings - Fork 1
/
LRU.js
60 lines (54 loc) · 1.36 KB
/
LRU.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
// LRU 缓存算法,最近使用
// () 正在使用的,[] 失效,容量为 4
// (1) 1
// (2) 2 1
// (4) 4 2 1
// (5) 5 4 2 1
// (6) 6 5 4 2 [1]
// (5) 5 6 4 2
const {DoubleLinked, Node} = require('./doubledLink')
class LRU {
constructor (opacity = 4) {
this.opacity = opacity
this.map = {}
this.doubleLink = new DoubleLinked()
}
size () {
return Object.keys(this.map).length
}
get (key) {
if (!(key in this.map)) return -1
const node = this.map[key]
this.doubleLink.remove(node)
this.doubleLink.appendFront(node)
return node.value
}
put (key, value) {
if (key in this.map) { // key 存在容量列表中
const originNode = this.map[key]
this.doubleLink.remove(originNode)
originNode.value = value
this.doubleLink.appendFront(originNode)
} else { // 不存在容量列表中
if (this.size() >= this.opacity) { // 缓存容量满了
const lastNode = this.doubleLink.remove()
delete this.map[lastNode.key]
}
const node = new Node(key, value)
this.doubleLink.appendFront(node)
this.map[key] = node
}
}
print () {
return this.doubleLink.print()
}
}
const l = new LRU(5)
l.put(1, 1) // (1) 1
l.put(2, 2) // (2) 2 1
l.put(3, 3) // (3) 3 2 1
l.put(4, 4) // (4) 4 3 2 1
l.put(5, 5) // (5) 5 4 3 2 [1]
l.print()
l.get(2) // (2) 2 5 4 3
l.print()