Operators matchematical

max

  1. let stream$ = Rx.Observable.of(5,4,7,-1)
  2. .max();

This emits 7. It’s obvious what this operator does, it gives us just one value, the max. There is different ways of calling it though. You can give it a comparer:

  1. function comparer(x,y) {
  2. if( x > y ) {
  3. return 1;
  4. } else if( x < y ) {
  5. return -1;
  6. } else return 0;
  7. }
  8. let stream$ = Rx.Observable.of(5,4,7,-1)
  9. .max(comparer);

In this case we define a comparer which runs a sort algorithm under the hood and all we have to do is to help it determine when something is larger than, equal or smaller than. Or with an object the idea is the same:

  1. function comparer(x,y) {
  2. if( x.age > y.age ) {
  3. return 1;
  4. } else if( x.age < y.age ) {
  5. return -1;
  6. } else return 0;
  7. }
  8. let stream$ = Rx.Observable.of({ name : 'chris', age : 37 }, { name : 'chross', age : 32 })
  9. .max(comparer);

Because we tell it in the comparer what property to compare we are left with the first entry as result.

min

Min is pretty much identical to max() operator but returns the opposite value, the smallest.

sum

sum() as operator has seized to exist but we can use reduce() for that instead like so:

  1. let stream$ = Rx.Observable.of(1,2,3,4)
  2. .reduce((accumulated, current) => accumulated + current )

This can be applied to objects as well as long as we define what the reduce() function should do, like so:

  1. let objectStream$ = Rx.Observable.of( { name : 'chris' }, { age : 11 } )
  2. .reduce( (acc,curr) => Object.assign({}, acc,curr ));

This will concatenate the object parts into an object.

average

The average() operator isn’t there anymore in Rxjs5 but you can still achieve the same thing with a reduce()

  1. let stream$ = Rx.Observable.of( 3, 6 ,9 )
  2. .map( x => { return { sum : x, counter : 1 } } )
  3. .reduce( (acc,curr) => {
  4. return Object.assign({}, acc, { sum : acc.sum + curr.sum ,counter : acc.counter + 1 })
  5. })
  6. .map( x => x.sum / x.counter )

I admit it, this one hurted my head a little, once you crack the initial map() call the reduce() is pretty simple, and Object.assign() is a nice companion as usual.