Open a-camuto opened 7 years ago
var movingAverage = function(data, window) { var limit = (window-1)/2 var moveMean = data.slice(0,limit); for (var i = limit; i < data.length-1-limit; i++) { var mean = 0 for (var j = 0; j <= limit; j++){
mean = mean + data[i-j] + data[i+j]
}
mean = mean/window
moveMean = moveMean.concat(mean);
} moveMean = moveMean.concat(data.slice(data.length-limit-1,data.length)); return moveMean }
`
let options = defaultOptions;
function calculator(data) {
const { windowSize, sourcePath } = options;
const source = path(sourcePath);
const alpha = 2 / (windowSize + 1);
let previous;
let initialAccumulator = 0;
let skip = 0;
return data.map(function(d, i) {
const v = source(d, i);
if (isNotDefined(previous) && isNotDefined(v)) {
skip++;
return undefined;
} else if (i < windowSize + skip - 1) {
initialAccumulator += v;
return undefined;
} else if (i === windowSize + skip - 1) {
initialAccumulator += v;
const initialValue = initialAccumulator / windowSize;
previous = initialValue;
return initialValue;
} else {
const nextValue = v * alpha + (1 - alpha) * previous;
previous = nextValue;
return nextValue;
}
});
}
calculator.undefinedLength = function() {
const { windowSize } = options;
return windowSize - 1;
};
calculator.options = function(x) {
if (!arguments.length) {
return options;
}
options = { ...defaultOptions, ...x };
return calculator;
};
return calculator;
`
Clever I like !
Usage -> data MUST be 1D. Window MUST be an odd number and inferior to length of data. As window size increase, the data is increasingly smooth. As window decreases (minimum of 1), granularity increases.
Haven't tested but skeleton is there/ inshallah will work.