Running average with rxjs 5
I would like to see moving 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 dataset it averages is
1,2,3,4
. - How could I average
1
both1,2
and and1,2,3
? - Play at https://jsfiddle.net/KristjanLaane/kLskp71j/
+3
source to share
2 answers
I would 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);
scan()
just collects at most 4 elements and then map()
calculates the average.
1
1.5
2
2.5
3.5
4.5
5.5
6.5
7.5
+3
source to share
My apologies for not being a JS coder, here is a C # answer. I would appreciate it if someone would translate for me.
var data = Observable.Range(1, 9);
var dataToAverage =
data
.Scan(new int[] { }, (a, x) => a.Take(3).StartWith(x).ToArray())
.Select(x => x.Average());
This gives:
1 1.5 2 2.5 3.5 4.5 5.5 6.5 7.5
+2
source to share