-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathcache.js
54 lines (40 loc) · 966 Bytes
/
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
/* eslint comma-dangle: ["warn", "never"] */
function Cache(expiration /* seconds */) {
this.entries = {};
this.expiration = 5;
if (expiration)
this.expiration = expiration;
}
Cache.prototype.get = function (key) {
const entry = this.entries[key];
if (entry)
return entry.value;
return undefined;
};
Cache.prototype.set = function (key, value) {
const timestamp = Date.now();
this.entries[key] = {
key,
value,
timestamp
};
};
Cache.prototype.has = function (key) {
return this.entries[key] !== undefined;
};
Cache.prototype.remove = function (key) {
delete this.entries[key];
};
Cache.prototype.expired = function (key) {
if (!this.has(key))
return true;
const entry = this.entries[key];
const delta = Math.abs(entry.timestamp - Date.now()) / 1000;
const seconds = delta % 60;
if (seconds > this.expiration) {
this.remove(key);
return true;
}
return false;
};
module.exports = Cache;