forked from holtzy/The-Python-Graph-Gallery
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathac.js
More file actions
106 lines (86 loc) · 2.09 KB
/
ac.js
File metadata and controls
106 lines (86 loc) · 2.09 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
module.exports = AsyncCache
var LRU = require('lru-cache')
function AsyncCache (opt) {
if (!opt || typeof opt !== 'object') {
throw new Error('options must be an object')
}
if (!opt.load) {
throw new Error('load function is required')
}
if (!(this instanceof AsyncCache)) {
return new AsyncCache(opt)
}
this._opt = opt
this._cache = new LRU(opt)
this._load = opt.load
this._loading = {}
this._stales = {}
this._allowStale = opt.stale
}
Object.defineProperty(AsyncCache.prototype, 'itemCount', {
get: function () {
return this._cache.itemCount
},
enumerable: true,
configurable: true
})
AsyncCache.prototype.get = function (key, cb) {
var stale = this._stales[key]
if (this._allowStale && stale !== undefined) {
return process.nextTick(function () {
cb(null, stale)
})
}
if (this._loading[key]) {
return this._loading[key].push(cb)
}
var has = this._cache.has(key)
var cached = this._cache.get(key)
if (has && undefined !== cached) {
return process.nextTick(function () {
cb(null, cached)
})
}
if (undefined !== cached && this._allowStale && !has) {
this._stales[key] = cached
process.nextTick(function () {
cb(null, cached)
})
} else {
this._loading[key] = [ cb ]
}
this._load(key, function (er, res, maxAge) {
if (!er) {
this._cache.set(key, res, maxAge)
}
if (this._allowStale) {
delete this._stales[key]
}
var cbs = this._loading[key]
if (!cbs) {
return
}
delete this._loading[key]
cbs.forEach(function (cb) {
cb(er, res)
})
}.bind(this))
}
AsyncCache.prototype.keys = function () {
return this._cache.keys()
}
AsyncCache.prototype.set = function (key, val, maxAge) {
return this._cache.set(key, val, maxAge)
}
AsyncCache.prototype.reset = function () {
return this._cache.reset()
}
AsyncCache.prototype.has = function (key) {
return this._cache.has(key)
}
AsyncCache.prototype.del = function (key) {
return this._cache.del(key)
}
AsyncCache.prototype.peek = function (key) {
return this._cache.peek(key)
}