Skip to content

Commit 5be5a0a

Browse files
committed
Add simple examples
1 parent fc40be3 commit 5be5a0a

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

JavaScript/1-function.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
'use strict';
2+
3+
const randomChar = () => String
4+
.fromCharCode(Math.floor((Math.random() * 25) + 97));
5+
6+
const subscribe = observer => {
7+
const observable = { observer };
8+
const timer = setInterval(() => {
9+
const char = randomChar();
10+
observer(char);
11+
}, 200);
12+
observable.complete = () => clearInterval(timer);
13+
return observable;
14+
};
15+
16+
// Usage
17+
18+
let count = 0;
19+
const observable = subscribe(observer);
20+
21+
function observer(char) {
22+
process.stdout.write(char);
23+
count++;
24+
if (count > 50) {
25+
observable.complete();
26+
process.stdout.write('\n');
27+
}
28+
}

JavaScript/2-class.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'use strict';
2+
3+
const randomChar = () => String
4+
.fromCharCode(Math.floor((Math.random() * 25) + 97));
5+
6+
class Observable {
7+
constructor() {
8+
this.timer = setInterval(() => {
9+
if (!this.onData) return;
10+
const char = randomChar();
11+
this.onData(char);
12+
}, 200);
13+
}
14+
subscribe(onData) {
15+
this.onData = onData;
16+
return this;
17+
}
18+
complete() {
19+
clearInterval(this.timer);
20+
}
21+
}
22+
23+
// Usage
24+
25+
let count = 0;
26+
const observable = new Observable().subscribe(char => {
27+
process.stdout.write(char);
28+
count++;
29+
if (count > 50) {
30+
observable.complete();
31+
process.stdout.write('\n');
32+
}
33+
});

0 commit comments

Comments
 (0)