Stream
by Paco86
JavaScript
class Stream {
constructor() {
this.fnArr = [];
this.secondStream = null;
this.secondFn = null;
}
subscribe(fn) {
this.fnArr.push(fn);
}
push(num) {
const newNum = this.secondFn(num);
this.secondStream.fnArr.forEach((fn) => {
fn(newNum);
})
}
map(fn) {
this.secondStream = new Stream();
this.secondFn = fn;
return this.secondStream;
}
}
// stream a -> 1--------2----3
// map \--------\----\
// push to b 2
// stream b -> 2--------4----6
const a = new Stream();
const b = a.map((value) => value * 2);
b.subscribe(console.log);
a.push(1);
a.push(2);
a.subscribe(console.log)
a.push(3);
// expected output on console:
// 2
// 4
// 3
// 6