forked from GerbenAaltink/alopex
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.js
More file actions
55 lines (49 loc) · 1.15 KB
/
cache.js
File metadata and controls
55 lines (49 loc) · 1.15 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
class Cache {
constructor (size) {
this._cached = {}
this.size = size // disabled
this.enabled = size > 0
this.hits = 0
this.misses = 0
this.recentKeys = []
}
_generateKey (params) {
return params.map(obj => JSON.stringify(obj)).join('_')
}
flush () {
this._cached = {}
}
_updateRecentKey (keyName) {
const index = this.recentKeys.indexOf(keyName)
if (index !== -1) {
this.recentKeys.splice(index, 1)
}
this.recentKeys.splice(0, 0, keyName)
}
_updateCache () {
if (this.recentKeys.length < this.size) {
return false
}
const recentKey = this.recentKeys.pop()
delete this._cached[recentKey]
return true
}
get (params, promise) {
if (!this.enabled) {
return promise()
}
const cacheKey = this._generateKey(params)
this._updateRecentKey(cacheKey)
if (this._cached[cacheKey] !== undefined) {
this.hits++
return Promise.resolve(this._cached[cacheKey])
}
return promise().then((value) => {
this.misses++
this._cached[cacheKey] = value
this._updateCache()
return value
})
}
}
module.exports = Cache