-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path3-function.js
More file actions
53 lines (41 loc) · 1.07 KB
/
3-function.js
File metadata and controls
53 lines (41 loc) · 1.07 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
'use strict';
const timeoutCollection = (interval) => {
const collection = new Map();
const timers = new Map();
const instance = {};
instance.set = (key, value) => {
const timer = timers.get(key);
if (timer) clearTimeout(timer);
const timeout = setTimeout(() => {
collection.delete(key);
}, interval);
timeout.unref();
collection.set(key, value);
timers.set(key, timer);
};
instance.get = (key) => collection.get(key);
instance.delete = (key) => {
const timer = timers.get(key);
if (timer) {
clearTimeout(timer);
collection.delete(key);
timers.delete(key);
}
};
instance.toArray = () => [...collection.entries()];
return instance;
};
// Usage
const hash = 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);