Skip to content

Instantly share code, notes, and snippets.

@fabriciofmsilva
Created March 15, 2018 22:04
Show Gist options
  • Save fabriciofmsilva/63085e75f53c63170cdc202ebeef76b9 to your computer and use it in GitHub Desktop.
Save fabriciofmsilva/63085e75f53c63170cdc202ebeef76b9 to your computer and use it in GitHub Desktop.
Build Your Own Operators Easily | RxJS
import { interval } from 'rxjs/observable/interval';
import { map, take, toArray } from 'rxjs/operators';
/**
* an operator that takes every Nth value
*/
const takeEveryNth = (n: number) => <T>(source: Observable<T>) =>
new Observable(observer => {
let count = 0;
return source.subscribe({
next(x) {
if (count++ % n === 0) observer.next(x);
},
error(err) { observer.error(err); },
complete() { observer.complete(); }
})
});
interval(1000).pipe(
takeEveryNth(2),
map(x => x + x),
takeEveryNth(3),
take(3),
toArray()
)
.subscribe(x => console.log(x));
// [0, 12, 24]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment