UNPKG

819 BJavaScriptView Raw
1// A cache that expires.
2module.exports = class Cache extends Map {
3 constructor(timeout = 1000) {
4 super();
5 this.timeout = timeout;
6 }
7 set(key, value) {
8 super.set(key, {
9 tid: setTimeout(this.delete.bind(this, key), this.timeout),
10 value,
11 });
12 }
13 get(key) {
14 let entry = super.get(key);
15 if (entry) {
16 return entry.value;
17 }
18 return null;
19 }
20 async getOrSet(key, fn) {
21 if (this.has(key)) {
22 return this.get(key);
23 } else {
24 let value = await fn();
25 this.set(key, value);
26 return value;
27 }
28 }
29 delete(key) {
30 let entry = super.get(key);
31 if (entry) {
32 clearTimeout(entry.tid);
33 super.delete(key);
34 }
35 }
36 clear() {
37 for (let entry of this.values()) {
38 clearTimeout(entry.tid);
39 }
40 super.clear();
41 }
42};