UNPKG

@thi.ng/transducers-stats

Version:

Transducers for statistical / technical analysis

28 lines (27 loc) 733 B
import { sliding } from "@thi.ng/buffers/sliding"; import { illegalArgs } from "@thi.ng/errors/illegal-arguments"; import { compR } from "@thi.ng/transducers/compr"; import { iterator1 } from "@thi.ng/transducers/iterator"; function sma(period, src) { if (src) { return iterator1(sma(period), src); } period |= 0; period < 1 && illegalArgs("period must be >= 1"); return (rfn) => { const reduce = rfn[2]; const window = sliding(period); let sum = 0; return compR(rfn, (acc, x) => { if (window.length === period) { sum -= window.read(); } window.write(x); sum += x; return window.length === period ? reduce(acc, sum / period) : acc; }); }; } export { sma };