-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy path9-functor.js
More file actions
33 lines (27 loc) · 796 Bytes
/
9-functor.js
File metadata and controls
33 lines (27 loc) · 796 Bytes
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
'use strict';
function Counter() {}
// TODO: check this code
const counter = (initial) => {
const f = (val) => {
f.count += val;
Object.keys(f.events).filter((n) => n <= f.count).forEach((n) => {
f.events[n].forEach((callback) => callback(f.count));
delete f.events[n];
});
return f;
};
Object.setPrototypeOf(f, Counter.prototype);
return Object.assign(f, { count: 0, events: {} })(initial);
};
Counter.prototype.on = function(n, callback) {
const event = this.events[n];
if (event) event.push(callback);
else this.events[n] = [callback];
return this(0);
};
// Usage
const c = counter(10);
c.on(5, (val) => console.log('Counter > 5, value:', val));
c.on(25, (val) => console.log('Counter > 25, value:', val));
c(5);
setTimeout(() => c(15), 100);