@thi.ng/transducers
Version:
Collection of ~170 lightweight, composable transducers, reducers, generators, iterators for functional data transformations
23 lines (22 loc) • 686 B
JavaScript
import { isIterable } from "@thi.ng/checks/is-iterable";
import { illegalArgs } from "@thi.ng/errors/illegal-arguments";
import { compR } from "./compr.js";
import { iterator1 } from "./iterator.js";
function movingAverage(period, src) {
return isIterable(src) ? iterator1(movingAverage(period), src) : (rfn) => {
period |= 0;
period < 2 && illegalArgs("period must be >= 2");
const reduce = rfn[2];
const window = [];
let sum = 0;
return compR(rfn, (acc, x) => {
const n = window.push(x);
sum += x;
n > period && (sum -= window.shift());
return n >= period ? reduce(acc, sum / period) : acc;
});
};
}
export {
movingAverage
};