-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
movingSum.ts
43 lines (35 loc) · 890 Bytes
/
movingSum.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
38
39
40
41
42
43
// Copyright (c) 2022 Onur Cinar. All Rights Reserved.
// https://github.com/cinar/indicatorts
/**
* Optional configuration of moving sum parameters.
*/
export interface MSumConfig {
period?: number;
}
/**
* The default configuration of moving sum.
*/
export const MSumDefaultConfig: Required<MSumConfig> = {
period: 4,
};
/**
* Moving sum of the given values.
* @param values values array.
* @param config configuration.
* @return sum values.
*/
export function msum(values: number[], config: MSumConfig = {}): number[] {
const { period } = { ...MSumDefaultConfig, ...config };
const result = new Array<number>(values.length);
let sum = 0;
for (let i = 0; i < values.length; i++) {
sum += values[i];
if (i >= period) {
sum -= values[i - period];
}
result[i] = sum;
}
return result;
}
// Export full name
export { msum as movingSum };