-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path5-operators.js
More file actions
65 lines (55 loc) · 1.28 KB
/
5-operators.js
File metadata and controls
65 lines (55 loc) · 1.28 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
'use strict';
class Observable {
constructor() {
this.observers = [];
this.operators = [];
}
subscribe(observer) {
this.observers.push(observer);
return this;
}
notify(data) {
if (this.observers.length === 0) return;
for (const operator of this.operators) {
if (operator.name === 'filter') {
if (!operator.fn(data)) return;
}
if (operator.name === 'map') {
data = operator.fn(data);
}
}
for (const observer of this.observers) {
observer(data);
}
}
filter(predicate) {
this.operators.push({ name: 'filter', fn: predicate });
return this;
}
map(callback) {
this.operators.push({ name: 'map', fn: callback });
return this;
}
}
const randomChar = () =>
String.fromCharCode(Math.floor(Math.random() * 25 + 97));
const observable = new Observable()
.filter((char) => !'aeiou'.includes(char))
.map((char) => char.toUpperCase());
setInterval(() => {
const char = randomChar();
observable.notify(char);
}, 200);
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();
observable.subscribe(observer);