UNPKG

@thi.ng/transducers-stats

Version:

Transducers for statistical / technical analysis

26 lines (25 loc) 676 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 momentum(period, src) { if (src) { return iterator1(momentum(period), src); } period |= 0; period < 1 && illegalArgs("period must be >= 1"); return (rfn) => { const reduce = rfn[2]; const window = sliding(period); return compR(rfn, (acc, x) => { if (window.length === period) { acc = reduce(acc, x - window.read()); } window.write(x); return acc; }); }; } export { momentum };