Created
May 4, 2017 00:26
-
-
Save jhusain/a7f4ca2ed5491d0b92a3be1783b8377c to your computer and use it in GitHub Desktop.
Observable implementation which optimizes very well in prepack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Observable(subscribe) { | |
this._subscribe = subscribe; | |
} | |
const of = (v) => new Observable(observer => { | |
return observer.next(v); | |
}); | |
Observable.prototype = { | |
map(f) { | |
return new Observable((observer) => { | |
return this.subscribe({ | |
next: (v) => observer.next(f(v)) | |
}); | |
}); | |
}, | |
filter(f) { | |
return new Observable((observer) => { | |
return this.subscribe({ | |
next: (v) => { | |
if (f(v)) { | |
observer.next(v); | |
} | |
} | |
}); | |
}); | |
}, | |
flatMap(f) { | |
return new Observable((observer) => { | |
return this.subscribe({ | |
next(v) { | |
const otherObs = f(v); | |
otherObs.subscribe(observer); | |
} | |
}); | |
}); | |
}, | |
subscribe(observer) { | |
return this._subscribe(observer); | |
} | |
}; | |
of(Math.random()). | |
flatMap((v) => of(Math.random())). | |
map((v) => v * Math.random()). | |
subscribe({ | |
next: (v) => console.log(v) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment