Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running average with rxjs 5

I would like to observe rolling averages with rxjs ^5

Half-solution

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);
  • The above code works fine, except that the first data array it averages is 1,2,3,4.
  • How could I average 1 and 1,2 and 1,2,3 as well?
  • Have a play at https://jsfiddle.net/KristjanLaane/kLskp71j/
like image 802
Cel Avatar asked Dec 24 '22 17:12

Cel


1 Answers

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
like image 181
martin Avatar answered Jan 14 '23 05:01

martin