-
Notifications
You must be signed in to change notification settings - Fork 723
/
cache.js
45 lines (45 loc) · 886 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
// A cache that expires.
module.exports = class Cache extends Map {
constructor(timeout = 1000) {
super();
this.timeout = timeout;
}
set(key, value) {
if (this.has(key)) {
clearTimeout(super.get(key).tid);
}
super.set(key, {
tid: setTimeout(this.delete.bind(this, key), this.timeout).unref(),
value,
});
}
get(key) {
let entry = super.get(key);
if (entry) {
return entry.value;
}
return null;
}
getOrSet(key, fn) {
if (this.has(key)) {
return this.get(key);
} else {
let value = fn();
this.set(key, value);
return value;
}
}
delete(key) {
let entry = super.get(key);
if (entry) {
clearTimeout(entry.tid);
super.delete(key);
}
}
clear() {
for (let entry of this.values()) {
clearTimeout(entry.tid);
}
super.clear();
}
};