-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
68 lines (58 loc) · 1.19 KB
/
index.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
57
58
59
60
61
62
63
64
65
66
67
68
function smooth (x1, x2, e) {
return x1 + e * (x2 - x1)
}
function Mean () {
var value = 0
var n = 0
var mean = function mean (x) {
if (!isNaN(x)) {
if (typeof x !== 'number') {
x = parseFloat(x)
}
n += 1
value = smooth(value, x, 1 / n)
} else if (Array.isArray(x)) {
x.forEach(el => mean(el))
}
return value
}
mean.fit = function (x) {
mean(x)
}
mean.setValue = function (newValue) {
value = newValue
}
mean.setN = function (newN) {
n = newN
}
Object.defineProperty(mean, 'value', {
get: function () {
return value
}
})
Object.defineProperty(mean, 'n', {
get: function () {
return n
}
})
return mean
}
Mean.merge = function merge () {
if (arguments.length) {
var mean = new Mean()
mean.setValue(arguments[0].value)
mean.setN(arguments[0].n)
for (var i = 1; i < arguments.length; i++) {
mean.setN(mean.n + arguments[i].n)
mean.setValue(smooth(
mean.value,
arguments[i].value,
arguments[i].n / mean.n
))
}
return mean
} else {
throw new Error('Provide arguments: Mean() objects')
}
}
module.exports = Mean