-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path4-emitter.js
More file actions
42 lines (34 loc) · 827 Bytes
/
4-emitter.js
File metadata and controls
42 lines (34 loc) · 827 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
'use strict';
const { EventEmitter } = require('node:events');
const randomChar = () =>
String.fromCharCode(Math.floor(Math.random() * 25 + 97));
class CharStream {
// Observable
constructor(ee, interval) {
this.timer = setInterval(() => {
const char = randomChar();
ee.emit('char', char);
}, interval);
}
complete() {
if (!this.timer) return;
clearInterval(this.timer);
this.timer = null;
}
}
const ee = new EventEmitter();
const observable = new CharStream(ee, 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();
ee.on('char', observer);
console.dir({ observer, observable });