|
5 | 5 | // Hint: Please consider scenarios when 'list' doesn't have numbers (the function is expected to return null) |
6 | 6 | // or 'list' has mixed values (the function is expected to sort only numbers). |
7 | 7 |
|
| 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 | + |
8 | 19 | 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 | + } |
12 | 51 | } |
13 | 52 |
|
14 | 53 | module.exports = calculateMedian; |
0 commit comments