-
-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathmedian.js
More file actions
33 lines (24 loc) · 944 Bytes
/
median.js
File metadata and controls
33 lines (24 loc) · 944 Bytes
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
// Fix this implementation
// Start by running the tests for this function
// If you're in the Sprint-1 directory, you can run `npm test -- fix` to run the tests in the fix directory
// Hint: Please consider scenarios when 'list' doesn't have numbers (the function is expected to return null)
// or 'list' has mixed values (the function is expected to sort only numbers).
function calculateMedian(list) {
if (!Array.isArray(list) || list.length === 0) {
return null;
}
const numbers = list.filter((item) => Number.isFinite(item));
if (numbers.length === 0) {
return null;
}
numbers.sort((a, b) => a - b);
const middleIndex = Math.floor(numbers.length / 2);
if (numbers.length % 2 !== 0) {
return numbers[middleIndex];
} else {
const leftMiddle = numbers[middleIndex - 1];
const rightMiddle = numbers[middleIndex];
return (leftMiddle + rightMiddle) / 2;
}
}
module.exports = calculateMedian;