-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
67 lines (59 loc) · 2 KB
/
script.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
const getMean = (array) => array.reduce((acc, el) => acc + el, 0) / array.length;
const getMedian = (array) => {
const sorted = array.slice().sort((a, b) => a - b);
const median =
array.length % 2 === 0
? getMean([sorted[array.length / 2], sorted[array.length / 2 - 1]])
: sorted[Math.floor(array.length / 2)];
return median;
}
const getMode = (array) => {
const counts = {};
array.forEach((el) => {
counts[el] = (counts[el] || 0) + 1;
})
if (new Set(Object.values(counts)).size === 1) {
return null;
}
const highest = Object.keys(counts).sort(
(a, b) => counts[b] - counts[a]
)[0];
const mode = Object.keys(counts).filter(
(el) => counts[el] === counts[highest]
);
return mode.join(", ");
}
const getRange = (array) => {
return Math.max(...array) - Math.min(...array);
}
const getVariance = (array) => {
const mean = getMean(array);
const variance = array.reduce((acc, el) => {
const difference = el - mean;
const squared = difference ** 2;
return acc + squared;
}, 0) / array.length;
return variance;
}
const getStandardDeviation = (array) => {
const variance = getVariance(array);
const standardDeviation = Math.sqrt(variance);
return standardDeviation;
}
const calculate = () => {
const value = document.querySelector("#numbers").value;
const array = value.split(/,\s*/g);
const numbers = array.map(el => Number(el)).filter(el => !isNaN(el));
const mean = getMean(numbers);
const median = getMedian(numbers);
const mode = getMode(numbers);
const range = getRange(numbers);
const variance = getVariance(numbers);
const standardDeviation = getStandardDeviation(numbers);
document.querySelector("#mean").textContent = mean;
document.querySelector("#median").textContent = median;
document.querySelector("#mode").textContent = mode;
document.querySelector("#range").textContent = range;
document.querySelector("#variance").textContent = variance;
document.querySelector("#standardDeviation").textContent = standardDeviation;
}