-
-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathmedian.js
More file actions
27 lines (20 loc) · 830 Bytes
/
median.js
File metadata and controls
27 lines (20 loc) · 830 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
// 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(n => typeof n === "number" && !Number.isNaN(n));
if (numbers.length === 0) {
return null;
}
const sorted = numbers.sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2
? sorted[mid]
: (sorted[mid - 1] + sorted[mid]) / 2;
}
module.exports = calculateMedian;