Skip to content

Commit 8ad77a6

Browse files
committed
Ignore this Commit
// It is not my solution I got help with AI. I confess I need to undestand more those 3 methodos to think how to get to this. // I will come back to it later. For now i will keep practicing more katas because they are help me.
1 parent 6cdb275 commit 8ad77a6

File tree

1 file changed

+42
-3
lines changed

1 file changed

+42
-3
lines changed

Sprint-1/fix/median.js

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,49 @@
55
// Hint: Please consider scenarios when 'list' doesn't have numbers (the function is expected to return null)
66
// or 'list' has mixed values (the function is expected to sort only numbers).
77

8+
// function calculateMedian(list) {
9+
// const middleIndex = Math.floor(list.length / 2);
10+
// const median = list.splice(middleIndex, 1)[0];
11+
// return median;
12+
// }
13+
14+
// Ignore this Commit
15+
// It is not my solution I got help with AI. I confess I need to undestand more those 3 methodos to think
16+
//and get to this solution
17+
// I will come back to it later.
18+
819
function calculateMedian(list) {
9-
const middleIndex = Math.floor(list.length / 2);
10-
const median = list.splice(middleIndex, 1)[0];
11-
return median;
20+
// non-array or empty inputs
21+
if (!Array.isArray(list) || list.length === 0) {
22+
return null;
23+
}
24+
25+
//Filter non-numeric values and create a new array of only numbers
26+
27+
const numericList = list.filter(
28+
(item) => typeof item === "number" && Number.isFinite(item)
29+
);
30+
31+
// If after filtering, there are no numbers left, return null
32+
if (numericList.length === 0) {
33+
return null;
34+
}
35+
36+
//Sort the numeric list
37+
const sortedList = [...numericList].sort((a, b) => a - b);
38+
39+
const middleIndex = Math.floor(sortedList.length / 2);
40+
41+
//Calculate the median based on list length (odd or even)
42+
if (sortedList.length % 2 === 1) {
43+
// Odd number of elements: return the middle element
44+
return sortedList[middleIndex];
45+
} else {
46+
// Even number of elements: return the average of the two middle elements
47+
const mid1 = sortedList[middleIndex - 1];
48+
const mid2 = sortedList[middleIndex];
49+
return (mid1 + mid2) / 2;
50+
}
1251
}
1352

1453
module.exports = calculateMedian;

0 commit comments

Comments
 (0)