Overview
A running transformation is a map transformation which keeps a running total or other record for each calculation. That is, it utilizes informaton from records before the current record, but not after. Moving Average Examples
The runningMovingAverage function takes a size parameter. It then creates the data structures needed to maintain the running total, and constructs the function used to calculate the moving average, which it returns. Because the moving average function is created within scope with the running total data structures, it has access to them and can read them and update them.
function runningMovingAverage(size){
let total = 0;
let items = [];
return function(item){
total += item;
items.push(item);
if(items.length>size){
let first = items.shift();
total -=first;
}
if(items.length === size) return total/size;
return null;
}
}
The moving average function is then used within the array map function.
let data = [{price:100},{price:101},{price:100},{price:102},{price:102},{price:103},{price:105},{price:102}];
let ma = runningMovingAverage(3);
let results = data.map(p=>{
return {
price:p.price,
movingAverage:ma(p.price)
}
});
Try it!