forked from pinpoint-apm/pinpoint-node-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple-cache.js
61 lines (50 loc) · 1.08 KB
/
simple-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
/**
* Pinpoint Node.js Agent
* Copyright 2020-present NAVER Corp.
* Apache License v2.0
*/
'use strict'
class SimpleCache {
constructor(maxCacheSize) {
this.cache = new Map()
this.maxCacheSize = maxCacheSize || 1024
}
getAll () {
return Array.from(this.cache.values())
}
get (key) {
if (key && this.cache.has(key)) {
const value = this.cache.get(key)
this.cache.delete(key)
this.cache.set(key, value)
return value
}
return null
}
put (key, value) {
if (!key || !value) return
if (this.cache.size >= this.maxCacheSize) {
this.deleteOldest()
}
this.cache.set(key, value)
return value
}
deleteOldest () {
const overSize = this.cache.size - this.maxCacheSize + 1
if (overSize > 0) {
const keys = Array.from(this.cache.keys()).slice(-overSize)
keys.forEach(key => this.cache.delete(key))
}
}
delete (key) {
if (!key) return
this.cache.delete(key)
}
size () {
return this.cache.size
}
isEmpty () {
return this.size() === 0
}
}
module.exports = SimpleCache