-
Notifications
You must be signed in to change notification settings - Fork 154
/
moving-average-from-data-stream.js
49 lines (43 loc) · 1.04 KB
/
moving-average-from-data-stream.js
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
47
48
49
/**
* Moving Average from Data Stream
*
* Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
*
* For example,
* MovingAverage m = new MovingAverage(3);
* m.next(1) = 1
* m.next(10) = (1 + 10) / 2
* m.next(3) = (1 + 10 + 3) / 3
* m.next(5) = (10 + 3 + 5) / 3
*/
/**
* Your MovingAverage object will be instantiated and called as such:
* var obj = Object.create(MovingAverage).createNew(size)
* var param_1 = obj.next(val)
*/
/**
* Initialize your data structure here.
* @param {number} size
*/
class MovingAverage {
constructor(size) {
this.window = Array(size).fill(0);
this.ptr = 0;
this.sum = 0;
this.count = 0;
}
/**
* @param {number} val
* @return {number}
*/
next(val) {
if (this.count < this.window.length) {
this.count++;
}
this.sum += val - this.window[this.ptr];
this.window[this.ptr] = val;
this.ptr = (this.ptr + 1) % this.window.length;
return this.sum / this.count;
}
}
export { MovingAverage };