Created
January 31, 2018 15:32
-
-
Save zenparsing/89f3a1ae89e996e145afcde0e8ade96b to your computer and use it in GitHub Desktop.
Observable: Take a random number of integers
This file contains hidden or 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* range(from, to) { | |
for (let i = from; i <= to; ++i) { | |
yield i; | |
} | |
} | |
function take(source, n) { | |
if (n <= 0) { | |
return Observable.from([]); | |
} | |
return new Observable(sink => { | |
let count = 0; | |
return source.subscribe({ | |
next(v) { | |
sink.next(v); | |
if (++count === n) { | |
sink.complete(); | |
} | |
}, | |
error(e) { sink.error(e) }, | |
complete() { sink.complete() }, | |
}); | |
}); | |
} | |
let observable = take( | |
Observable.from(range(0, Number.POSITIVE_INFINITY)), | |
Math.round(Math.random() * 100) | |
); | |
observable.subscribe(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment