-
-
Notifications
You must be signed in to change notification settings - Fork 150
/
sma.ts
37 lines (36 loc) · 1.16 KB
/
sma.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { DCons } from "@thi.ng/dcons";
import { illegalArgs } from "@thi.ng/errors";
import { compR, iterator1, Reducer, Transducer } from "@thi.ng/transducers";
/**
* Like {@link @thi.ng/transducers#(movingAverage:1)}, but using more
* efficient linked list as sliding window buffer.
*
* Note: the number of results will be `period-1` less than the number
* of processed inputs.
*
* @param period -
*/
export function sma(period: number): Transducer<number, number>;
export function sma(
period: number,
src: Iterable<number>
): IterableIterator<number>;
export function sma(period: number, src?: Iterable<number>): any {
if (src) {
return iterator1(sma(period), src);
}
period |= 0;
period < 2 && illegalArgs("period must be >= 2");
return (rfn: Reducer<any, number>) => {
const reduce = rfn[2];
const window = new DCons<number>();
let sum = 0;
return compR(rfn, (acc, x: number) => {
window.push(x);
const n = window.length;
sum += x;
n > period && (sum -= window.drop()!);
return n >= period ? reduce(acc, sum / period) : acc;
});
};
}