forked from npm/node-semver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlrucache.js
More file actions
71 lines (58 loc) · 1.23 KB
/
lrucache.js
File metadata and controls
71 lines (58 loc) · 1.23 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
class LRUCache {
constructor (max = 0) {
if (!Number.isInteger(max) || max < 0) {
throw new TypeError('max must be a nonnegative integer')
}
this.max = max
this.map = new Map()
}
get (key) {
const value = this.map.get(key)
if (value === undefined) {
return undefined
} else {
// Remove the key from the map and add it to the end
this.map.delete(key)
this.map.set(key, value)
return value
}
}
has (key) {
return this.map.has(key)
}
delete (key) {
if (this.map.has(key)) {
this.map.delete(key)
return true
} else {
return false
}
}
set (key, value) {
const deleted = this.delete(key)
if (!deleted && value !== undefined) {
// If cache is full, delete the least recently used item
if (this.map.size >= this.max) {
const firstKey = this.map.keys().next().value
this.delete(firstKey)
}
this.map.set(key, value)
}
return this
}
clear () {
this.map.clear()
}
capacity () {
return this.max
}
size () {
return this.map.size
}
* entries () {
for (const [key, value] of this.map) {
yield [key, value]
}
}
}
module.exports = LRUCache