forked from sdwilsh/tree-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
temporalcache.js
43 lines (39 loc) · 892 Bytes
/
temporalcache.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
var assert = require("assert");
// Default is hours
var kMSPerCacheUnit = 1000 * 60 * 60;
function Cache()
{
this.cache = {};
}
Cache.prototype = {
has: function (name) {
return this.cache.hasOwnProperty(name);
},
get: function (name) {
if (this.has(name)) {
return this._get(name).value;
}
return undefined;
},
_get: function (name) {
assert.ok(this.has(name));
return this.cache[name];
},
add: function (name, value, time) {
if (this.has(name))
this.remove(name);
this.cache[name] = {
value: value,
timer: setTimeout(this.remove.bind(this, name), kMSPerCacheUnit * time)
};
},
remove: function (name) {
assert.ok(this.has(name));
var entry = this._get(name);
if (entry.timer)
clearTimeout(entry.timer);
delete this.cache[name];
return entry.value;
},
};
module.exports = Cache;