forked from Disciplr-Org/Disciplr-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmovingAverage.ts
More file actions
31 lines (30 loc) · 1.04 KB
/
Copy pathmovingAverage.ts
File metadata and controls
31 lines (30 loc) · 1.04 KB
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
/**
* movingAverage.ts
*
* Pure, deterministic trailing moving-average utility.
*/
/**
* Compute a trailing moving average over a numeric series.
*
* For each index i the average is taken over the window
* [max(0, i - window + 1), i] (inclusive), so partial windows are used
* at the start of the series rather than returning null/undefined.
*
* Edge cases:
* - Empty series → returns [].
* - window ≤ 0 → treated as window = 1 (identity).
* - window > series length → partial window used for all points.
*
* @param values - Input numeric series.
* @param window - Number of data points to include in the trailing window.
* @returns Array of the same length as `values` with smoothed values.
*/
export function movingAverage(values: number[], window: number): number[] {
if (values.length === 0) return [];
const w = Math.max(1, window);
return values.map((_, i) => {
const start = Math.max(0, i - w + 1);
const slice = values.slice(start, i + 1);
return slice.reduce((sum, v) => sum + v, 0) / slice.length;
});
}