Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@zenparsing
Created January 31, 2018 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zenparsing/89f3a1ae89e996e145afcde0e8ade96b to your computer and use it in GitHub Desktop.
Save zenparsing/89f3a1ae89e996e145afcde0e8ade96b to your computer and use it in GitHub Desktop.
Observable: Take a random number of integers
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