Last active
April 21, 2019 11:17
-
-
Save kosich/f649d408cfdad2c560ad70031354f0af to your computer and use it in GitHub Desktop.
custom operator filterChanges to filter only increasing numbers
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
const { rxObserver } = require('api/v0.3'); | |
const { timer, from, of, EMPTY, pipe } = require('rxjs'); | |
const { zip, startWith, pairwise, switchMap, filter } = require('rxjs/operators'); | |
// create a source using values | |
const values$ = from([ 5, 10, 20, 10, 5, 20, 0, 5 ]); | |
const source$ = timer(0, 10).pipe( | |
zip(values$, (_,x)=>x) | |
); | |
// it will take a predicate to compare values | |
// by default it will behave as distinctUntilChanged() | |
const filterChanges = (predicate = ((a,b) => a!==b)) => { | |
// store previous value | |
let prevValue = void 0; | |
return pipe( | |
filter((value, index)=>{ | |
// pass through the first value | |
if (index === 0) { | |
prevValue = value; | |
return value; | |
} | |
// compare current with prev | |
const result = predicate(value, prevValue); | |
prevValue = value; | |
return result; | |
}) | |
); | |
}; | |
// compare values pairwise | |
const result$ = source$.pipe( | |
filterChanges((a, b) => a > b) | |
); | |
source$.subscribe(rxObserver('source$')); | |
result$.subscribe(rxObserver('result$')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment