Skip to content

Commit cfbdeb3

Browse files
committed
Facade example for Map and Map or Timers
1 parent e971479 commit cfbdeb3

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

JavaScript/1-prototype.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
'use strict';
2+
3+
// Facade for Map and Map or Timers
4+
5+
const TimeoutCollection = function(timeout) {
6+
this.timeout = timeout;
7+
this.collection = new Map();
8+
this.timers = new Map();
9+
};
10+
11+
TimeoutCollection.prototype.set = function(key, value) {
12+
const timer = this.timers.get(key);
13+
if (timer) clearTimeout(timer);
14+
const timeout = setTimeout(() => {
15+
this.delete(key);
16+
}, this.timeout);
17+
this.collection.set(key, value);
18+
this.timers.set(key, timeout);
19+
};
20+
21+
TimeoutCollection.prototype.get = function(key) {
22+
return this.collection.get(key);
23+
};
24+
25+
TimeoutCollection.prototype.delete = function(key) {
26+
const timer = this.timers.get(key);
27+
if (timer) {
28+
clearTimeout(timer);
29+
this.collection.delete(key);
30+
this.timers.delete(key);
31+
}
32+
};
33+
34+
TimeoutCollection.prototype.toArray = function() {
35+
return [...this.collection.entries()];
36+
};
37+
38+
// Usage
39+
40+
const hash = new TimeoutCollection(1000);
41+
hash.set('uno', 1);
42+
setTimeout(() => {
43+
hash.set('due', 2);
44+
hash.set('tre', 3);
45+
console.dir({ array: hash.toArray() });
46+
}, 1500);

README.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
1-
# Facade
2-
Pattern Facade Implementations
1+
# Pattern Facade Implementations

0 commit comments

Comments
 (0)