-
Notifications
You must be signed in to change notification settings - Fork 2
/
wstat.js
56 lines (43 loc) · 1.19 KB
/
wstat.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
50
51
52
53
54
55
56
var _ = require('underscore');
var util = require('util');
function Wstat(params){
this.weight = 'weight';
this.value = 'value';
_.extend(this, params);
_.defaults(this, {values: []});
}
module.exports = Wstat;
Wstat.prototype = {
w_avg: function(){
var weights = 0;
var sum = 0;
var self = this;
this.values.forEach(function(item){
var value = 0;
var weight = 1;
if (item.hasOwnProperty(self.value)){
value = item[self.value];
};
if (item.hasOwnProperty(self.weight)){
weight = item[self.weight];
}
if (isNaN(value) || isNaN(weight) || (!isFinite(value)) || (!isFinite(weight))){
return;
}
if (weight <= 0){
return;
}
weights += weight;
sum += value * weight;
});
if (weights <= 0){
return 0;
}
var out = sum / weights;
if (isNaN(out) || (!isFinite(out))){
console.log('w_avg isNaN: %s', util.inspect(this.values));
return 0;
}
return out;
}
}