I would like to observe rolling averages with rxjs ^5
const data$ = Rx.Observable.range(1, 9);
const dataToAverage$ = data$.bufferCount(4, 1);
const movingAverage$ = dataToAverage$.map(arr =>
arr.reduce((acc, cur) => acc + cur) / arr.length);
1,2,3,4
.1
and 1,2
and 1,2,3
as well?I'd do it like this:
Observable.range(1, 9)
.scan((acc, curr) => {
acc.push(curr);
if (acc.length > 4) {
acc.shift();
}
return acc;
}, [])
.map(arr => arr.reduce((acc, current) => acc + current, 0) / arr.length)
.subscribe(console.log);
The scan()
just collects at most 4 items and the map()
then calculates the average.
1
1.5
2
2.5
3.5
4.5
5.5
6.5
7.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With