-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path2-class.js
More file actions
56 lines (46 loc) · 1.08 KB
/
2-class.js
File metadata and controls
56 lines (46 loc) · 1.08 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
'use strict';
class TimeoutCollection {
constructor(timeout) {
this.timeout = timeout;
this.collection = new Map();
this.timers = new Map();
}
set(key, value) {
const timer = this.timers.get(key);
if (timer) clearTimeout(timer);
const timeout = setTimeout(() => {
this.delete(key);
}, this.timeout);
timeout.unref();
this.collection.set(key, value);
this.timers.set(key, timeout);
}
get(key) {
return this.collection.get(key);
}
delete(key) {
const timer = this.timers.get(key);
if (timer) {
clearTimeout(timer);
this.collection.delete(key);
this.timers.delete(key);
}
}
toArray() {
return [...this.collection.entries()];
}
}
// Usage
const hash = new TimeoutCollection(1000);
hash.set('uno', 1);
console.dir({ array: hash.toArray() });
hash.set('due', 2);
console.dir({ array: hash.toArray() });
setTimeout(() => {
hash.set('tre', 3);
console.dir({ array: hash.toArray() });
setTimeout(() => {
hash.set('quattro', 4);
console.dir({ array: hash.toArray() });
}, 500);
}, 1500);