-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path3-pure-oop.js
More file actions
71 lines (60 loc) · 1.33 KB
/
3-pure-oop.js
File metadata and controls
71 lines (60 loc) · 1.33 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
'use strict';
class Observable {
constructor() {
this.observers = [];
}
subscribe(observer) {
observer.observable = this;
this.observers.push(observer);
return this;
}
notify(data) {
if (this.observers.length === 0) return;
for (const observer of this.observers) {
observer.update(data);
}
}
complete() {
throw new Error('Observable.complete is not implemented');
}
}
class Observer {
update() {
throw new Error('Observer.update is not implemented');
}
}
const randomChar = () =>
String.fromCharCode(Math.floor(Math.random() * 25 + 97));
class CharStream extends Observable {
constructor(interval) {
super();
this.timer = setInterval(() => {
const char = randomChar();
this.notify(char);
}, interval);
}
complete() {
if (!this.timer) return;
clearInterval(this.timer);
this.timer = null;
}
}
class CharStreamObserver extends Observer {
constructor() {
super();
this.count = 0;
this.observable = null;
}
update(char) {
process.stdout.write(char);
this.count++;
if (this.count > 50) {
this.observable.complete();
process.stdout.write('\n');
}
}
}
const observer = new CharStreamObserver();
const observable = new CharStream(200);
observable.subscribe(observer);
console.dir({ observer, observable });