-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRU.js
More file actions
76 lines (54 loc) · 1.4 KB
/
Copy pathLRU.js
File metadata and controls
76 lines (54 loc) · 1.4 KB
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
const Node = require('./structure/Node')
const DoubleList = require('./structure/DoubleList')
class Cache_LRU {
constructor(cap = 50) {
this.doubleList = new DoubleList()
this.map = new Map()
this.cap = cap
}
get(key) {
if (!this.map.has(key)) {
return null
}
this._makeRecently(key)
return this.map.get(key).val
}
put(key, val) {
if (this.map.has(key)) {
this._deleteKey(key)
this._addRecently(key, val)
return
}
if (this.cap == this.doubleList.size) {
this._removeLeastRencently()
}
this._addRecently(key, val)
}
get keys() {
return this.map.keys()
}
//将某个 key 提升为最近使⽤的
_makeRecently(key) {
let x = this.map.get(key)
this.doubleList.remove(x)
this.doubleList.push(x)
}
// 添加最近使⽤的元素
_addRecently(key, val) {
let x = new Node(key, val)
this.doubleList.push(x)
this.map.set(key, x)
}
// 删除某⼀个 key
_deleteKey(key) {
x = this.map.get(key)
this.doubleList.remove(x)
this.map.delete(key)
}
// 删除最久未使⽤的元素
_removeLeastRencently() {
let x = this.doubleList.shift()
this.map.delete(x.key)
}
}
module.exports = Cache_LRU