-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path2-class.js
More file actions
44 lines (37 loc) · 865 Bytes
/
2-class.js
File metadata and controls
44 lines (37 loc) · 865 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
34
35
36
37
38
39
40
41
42
43
44
'use strict';
const randomChar = () =>
String.fromCharCode(Math.floor(Math.random() * 25 + 97));
class Observable {
constructor(interval) {
this.observer = null;
this.timer = setInterval(() => {
if (!this.observer) return;
const char = randomChar();
this.observer(char);
}, interval);
}
subscribe(observer) {
this.observer = observer;
return this;
}
unsubscribe() {
if (!this.timer) return;
clearInterval(this.timer);
this.timer = null;
}
}
const createObserver = () => {
let count = 0;
return (char) => {
process.stdout.write(char);
count++;
if (count > 50) {
process.stdout.write('\n');
process.exit(0);
}
};
};
const observer = createObserver();
const observable = new Observable(200);
observable.subscribe(observer);
console.dir({ observer, observable });