-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
88 lines (73 loc) · 1.87 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
'use strict';
/*global module:true*/
let mean = numbers => {
if (!Array.isArray(numbers)) {
return null;
}
return numbers.reduce((pv, cv) => pv + cv, 0) / numbers.length;
};
let median = numbers => {
if (!Array.isArray(numbers)) {
return null;
}
let median = 0, numsLen = numbers.length;
numbers.sort();
if (numbers.length % 2 == 0) {
median = (numbers[numsLen / 2 - 1] + numbers[numsLen / 2]) / 2;
} else {
median = numbers[(numsLen - 1) / 2];
}
return median;
};
let mode = numbers => {
if (!Array.isArray(numbers)) {
return null;
}
let modes = [], count = [], maxIndex = 0;
for (let value of numbers) {
count[value] = (count[value] || 0) + 1;
if (count[value] > maxIndex)
maxIndex = count[value];
}
for (let i of numbers) {
if (count.hasOwnProperty(i)) {
if (count[i] === maxIndex) {
modes.push(Number(i));
}
}
}
return modes;
};
let standardDeviation = numbers => {
return Math.sqrt(variance(numbers));
};
let variance = numbers => {
if (!Array.isArray(numbers)) {
return null;
}
let initialMean = mean(numbers);
let varianceNumbersArray = [];
for (let value of numbers) {
let varianceNumber = value - initialMean;
varianceNumbersArray.push(varianceNumber * varianceNumber);
}
let variance = mean(varianceNumbersArray);
return variance;
};
let harmonicMean = numbers => {
if (!Array.isArray(numbers)) {
return null;
}
let total = numbers.reduce(function(sum, value) {
return sum + (1/value);
}, 0);
return numbers.length/total;
};
module.exports = {
mean: mean,
median: median,
mode: mode,
standardDeviation: standardDeviation,
variance: variance,
harmonicMean: harmonicMean
};