-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaverageRing.js
More file actions
78 lines (60 loc) · 1.74 KB
/
averageRing.js
File metadata and controls
78 lines (60 loc) · 1.74 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
var AverageRing = function(size, calculateDiff) {
this.size = parseInt(size);
this.nextPosition = 0;
this.used = 0;
this.full = false;
this.ring = new Array(this.size);
this.lastValue = 0;
this.calcDiff = calculateDiff === undefined ? true : false;
};
AverageRing.prototype.add = function(value) {
if (!this.full) {
if (++this.used === this.size) {
this.full = true;
}
}
this.ring[this.nextPosition] = {
value: this.calcDiff ? value - this.lastValue : value,
time: new Date()
};
if (this.calcDiff) {
this.lastValue = value;
}
this.positionStep();
}
AverageRing.prototype.positionStep = function() {
this.nextPosition = (++this.nextPosition) % (this.size);
}
AverageRing.prototype.getAverage = function(precision) {
var avg = 0;
var l = this.used;
if (l === 0) {
return 0;
}
precision = Math.pow(10, precision);
for (var i = 0; i < l; i++) {
var item = this.ring[i];
avg += item.value;
}
avg = avg / l;
return Math.floor(avg * precision) / precision;
}
AverageRing.prototype.getAveragePerTime = function(precision, projectionTimeMs) {
var avg = 0;
var l = this.used;
var minTime = new Date().getTime();
var maxTime = 0;
if (l === 0) {
return 0;
}
precision = Math.pow(10, precision);
for (var i = 0; i < l; i++) {
var item = this.ring[i];
avg += item.value;
minTime = Math.min(minTime, item.time.getTime());
maxTime = Math.max(maxTime, item.time.getTime());
}
var timeDiff = maxTime - minTime;
return Math.floor((avg / timeDiff) * projectionTimeMs * precision) / precision;
}
module.exports = AverageRing;