Skip to content

Commit 6869ef3

Browse files
committed
Add prototype-programming example
1 parent e8f8eab commit 6869ef3

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

JavaScript/3-prototype.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'use strict';
2+
3+
class Interval {
4+
static timers = new Map();
5+
6+
constructor(msec, callback) {
7+
this.callback = callback;
8+
const timer = Interval.timers.get(msec);
9+
if (timer) {
10+
Object.setPrototypeOf(this, timer);
11+
} else {
12+
this.listeners = new Set();
13+
this.instance = setInterval(() => {
14+
for (const callback of this.listeners.values()) {
15+
callback();
16+
}
17+
}, msec);
18+
Interval.timers.set(msec, this);
19+
}
20+
this.listeners.add(this.callback);
21+
}
22+
23+
remove() {
24+
this.listeners.delete(this.callback);
25+
if (this.listeners.length === 0) {
26+
clearInterval(this.instance);
27+
Interval.timers.delete(this);
28+
}
29+
}
30+
}
31+
32+
// Usage
33+
34+
const COUNT = 1000000;
35+
for (let i = 0; i < COUNT; i++) {
36+
new Interval(1000, () => {});
37+
new Interval(2000, () => {});
38+
}
39+
const memory = process.memoryUsage();
40+
console.log({ memory });

0 commit comments

Comments
 (0)