-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstats.js
More file actions
50 lines (40 loc) · 1.1 KB
/
stats.js
File metadata and controls
50 lines (40 loc) · 1.1 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
exports.max = (numbers) => Math.max(...numbers);
exports.min = (numbers) => Math.min(...numbers);
// exports.avg = (numbers) =>
// numbers.reduce(
// (acc, current, index, array) =>
// index === array.length - 1
// ? (acc + current) / array.length
// : acc + current,
// 0
// );
exports.avg = (numbers) =>
numbers.reduce(
(acc, current, index, { length }) => acc + current / length,
0
);
exports.sort = (numbers) => numbers.sort((a, b) => a - b);
exports.median = (numbers) => {
const { length } = numbers;
const middle = Math.floor(length / 2);
return length % 2
? numbers[middle]
: (numbers[middle - 1] + numbers[middle]) / 2;
};
exports.mode = (numbers) => {
const counts = numbers.reduce(
(acc, current) => acc.set(current, acc.get(current) + 1 || 1),
new Map()
);
const maxCount = Math.max(...counts.values());
const modes = [...counts.keys()].filter(
(number) => counts.get(number) === maxCount
);
if (modes.length === numbers.length) {
return null;
}
if (modes.length > 1) {
return modes;
}
return modes[0];
};