Skip to content

Instantly share code, notes, and snippets.

@kosich
Last active April 21, 2019 11:17
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 kosich/f649d408cfdad2c560ad70031354f0af to your computer and use it in GitHub Desktop.
Save kosich/f649d408cfdad2c560ad70031354f0af to your computer and use it in GitHub Desktop.
custom operator filterChanges to filter only increasing numbers
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