-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsampling.ts
46 lines (41 loc) · 1.15 KB
/
sampling.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
44
45
46
/**
* smooth sampling tool
*/
export class SmoothSampling {
private maxSampleCount: number;
private samples: number[] = [];
private currentSampleIndex = 0;
private average = 0;
/**
* create a smooth sampling tool instance
* @param maxSampleCount max count of samples to keep for smoothing
*/
constructor(maxSampleCount: number) {
this.maxSampleCount = maxSampleCount;
}
/**
* append a new sample value
* @param sample sample value to add
*/
public append(sample: number): void {
const { samples, currentSampleIndex } = this;
samples[currentSampleIndex] = sample;
// update average
let total = 0;
const len = samples.length;
for (let i = 0; i < len; i += 1) {
total += samples[i];
}
this.average = total / len;
// save average
samples[currentSampleIndex] = this.average;
this.currentSampleIndex = (currentSampleIndex + 1) % this.maxSampleCount;
}
/**
* get smooth average value
* @returns the average value
*/
public get(): number {
return this.average;
}
}