Skip to content

Commit c2c49eb

Browse files
committed
Completed exercise in fix directory
1 parent cfd674c commit c2c49eb

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

Sprint-1/fix/median.js

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,29 @@
66
// or 'list' has mixed values (the function is expected to sort only numbers).
77

88
function calculateMedian(list) {
9-
const middleIndex = Math.floor(list.length / 2);
10-
const median = list.splice(middleIndex, 1)[0];
11-
return median;
9+
// Check if input is an array
10+
if (!Array.isArray(list)) {
11+
return null;
12+
} else {
13+
// Get only numeric values
14+
const numericList = list.filter((item) => typeof item === "number");
15+
// Check if its empty after filtering
16+
if (numericList.length === 0) {
17+
return null;
18+
}
19+
// Sort the list by numeric value
20+
numericList.sort((a, b) => a - b);
21+
// Get middle index
22+
const middleIndex = Math.floor(numericList.length / 2);
23+
// Check if length is even or odd
24+
if (numericList.length % 2 === 0) {
25+
// Return average of two middle numbers
26+
return (numericList[middleIndex - 1] + numericList[middleIndex]) / 2;
27+
} else {
28+
// Return middle number by index
29+
return numericList[middleIndex];
30+
}
31+
}
1232
}
1333

1434
module.exports = calculateMedian;

0 commit comments

Comments
 (0)