Skip to content

Commit 7a85f60

Browse files
committed
Add counter functional object
1 parent f2fbac8 commit 7a85f60

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

JavaScript/8-counter.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'use strict';
2+
3+
function Counter() {}
4+
5+
const counter = initial => {
6+
const f = val => {
7+
f.count += val;
8+
Object.keys(f.events)
9+
.map(key => parseInt(key))
10+
.filter(n => n <= f.count)
11+
.forEach(n => {
12+
f.events[n].forEach(callback => callback(f.count));
13+
delete f.events[n];
14+
});
15+
return f;
16+
};
17+
const fields = { count: 0, events: {} };
18+
Object.setPrototypeOf(f, Counter.prototype);
19+
Object.assign(f, fields);
20+
return f(initial);
21+
};
22+
23+
Counter.prototype.on = function(n, callback) {
24+
const event = this.events[n];
25+
if (event) event.push(callback);
26+
else this.events[n] = [callback];
27+
return this(0);
28+
};
29+
30+
// Usage
31+
32+
const c = counter(10);
33+
c.on(5, val => console.log('Counter > 5, value:', val));
34+
c.on(5, val => console.log('Counter > 5, value:', val));
35+
c.on(25, val => console.log('Counter > 25, value:', val));
36+
c(5);
37+
setTimeout(() => c(15), 100);
File renamed without changes.

0 commit comments

Comments
 (0)