sum

There used to be an operator called sum(), but it hasn't existed for several versions. What there is instead is .reduce(). With the reduce() operator, we can easily achieve the same thing. The following is how you would write a sum() operator using reduce():

// mathematical/sum.js

let stream = Rx.Observable.of(1, 2, 3, 4)
.reduce((acc, curr) => acc + curr);

// emits 10
stream.subscribe(data => console.log(data));

What this does is to loop through all the emitted values and sum up the results. So, in essence, it sums up everything. Of course, this kind of operator can not only be applied to numbers, but to objects as well. The difference lies in how you carry out the reduce() operation. The following example covers such a scenario:

let stream = Rx.Observable.of({ name : "chris" }, { age: 38 })
.reduce((acc, curr) => Object.assign({},acc, curr));

// { name: 'chris', age: 38 }
stream.subscribe(data => console.log(data));

As you can see from the preceding code, the reduce() operator ensures that all the object's properties get merged together into one object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.168.2