forked from Binaryify/NeteaseCloudMusicApi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory-cache.js
63 lines (47 loc) · 1.13 KB
/
memory-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
62
63
function MemoryCache() {
this.cache = {}
this.size = 0
}
MemoryCache.prototype.add = function (key, value, time, timeoutCallback) {
var old = this.cache[key]
var instance = this
var entry = {
value: value,
expire: time + Date.now(),
timeout: setTimeout(function () {
instance.delete(key)
return (
timeoutCallback &&
typeof timeoutCallback === 'function' &&
timeoutCallback(value, key)
)
}, time),
}
this.cache[key] = entry
this.size = Object.keys(this.cache).length
return entry
}
MemoryCache.prototype.delete = function (key) {
var entry = this.cache[key]
if (entry) {
clearTimeout(entry.timeout)
}
delete this.cache[key]
this.size = Object.keys(this.cache).length
return null
}
MemoryCache.prototype.get = function (key) {
var entry = this.cache[key]
return entry
}
MemoryCache.prototype.getValue = function (key) {
var entry = this.get(key)
return entry && entry.value
}
MemoryCache.prototype.clear = function () {
Object.keys(this.cache).forEach(function (key) {
this.delete(key)
}, this)
return true
}
module.exports = MemoryCache