-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path1-prototype.js
More file actions
57 lines (46 loc) · 1.32 KB
/
1-prototype.js
File metadata and controls
57 lines (46 loc) · 1.32 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
57
'use strict';
// Facade that wraps Map and Node.js Timers to provide a simple interface for a
// collection with values that have expiration timeout.
const TimeoutCollection = function (timeout) {
this.timeout = timeout;
this.collection = new Map();
this.timers = new Map();
};
TimeoutCollection.prototype.set = function (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);
};
TimeoutCollection.prototype.get = function (key) {
return this.collection.get(key);
};
TimeoutCollection.prototype.delete = function (key) {
const timer = this.timers.get(key);
if (timer) {
clearTimeout(timer);
this.collection.delete(key);
this.timers.delete(key);
}
};
TimeoutCollection.prototype.toArray = function () {
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);