Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 44a6c6b

Browse filesBrowse files
committed
Simple operators: filter and map
1 parent 2779f3f commit 44a6c6b
Copy full SHA for 44a6c6b

File tree

Expand file treeCollapse file tree

1 file changed

+60
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+60
-0
lines changed

‎JavaScript/5-operators.js

Copy file name to clipboard
+60Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
'use strict';
2+
3+
class Observable {
4+
constructor() {
5+
this.observers = [];
6+
this.operators = [];
7+
}
8+
subscribe(observer) {
9+
this.observers.push(observer);
10+
return this;
11+
}
12+
notify(data) {
13+
if (this.observers.length === 0) return;
14+
for (const operator of this.operators) {
15+
if (operator.name === 'filter') {
16+
if (!operator.fn(data)) return;
17+
}
18+
if (operator.name === 'map') {
19+
data = operator.fn(data);
20+
}
21+
}
22+
for (const observer of this.observers) {
23+
observer(data);
24+
}
25+
}
26+
filter(predicate) {
27+
this.operators.push({ name: 'filter', fn: predicate });
28+
return this;
29+
}
30+
map(callback) {
31+
this.operators.push({ name: 'map', fn: callback });
32+
return this;
33+
}
34+
}
35+
36+
// Usage
37+
38+
const randomChar = () => String
39+
.fromCharCode(Math.floor((Math.random() * 25) + 97));
40+
41+
let count = 0;
42+
43+
const observable = new Observable()
44+
.filter(char => !'aeiou'.includes(char))
45+
.map(char => char.toUpperCase())
46+
.subscribe(observer);
47+
48+
const timer = setInterval(() => {
49+
const char = randomChar();
50+
observable.notify(char);
51+
}, 200);
52+
53+
function observer(char) {
54+
process.stdout.write(char);
55+
count++;
56+
if (count > 50) {
57+
clearInterval(timer);
58+
process.stdout.write('\n');
59+
}
60+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.