diff --git a/Sprint-1/fix/median.js b/Sprint-1/fix/median.js index b22590bc6..eddd77fc6 100644 --- a/Sprint-1/fix/median.js +++ b/Sprint-1/fix/median.js @@ -1,13 +1,24 @@ -// 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 +function calculateMedian(list) { + const numbers = []; + for (const x of list) { + if (typeof x === "number") { + numbers.push(x); + } + } + if (numbers.length === 0 || list.length === 0) { + return null; + } -// 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). + numbers.sort((a, b) => a - b); + const middleIndex = Math.floor(numbers.length / 2); -function calculateMedian(list) { - const middleIndex = Math.floor(list.length / 2); - const median = list.splice(middleIndex, 1)[0]; + if (numbers.length % 2 === 0) { + const left = numbers[middleIndex - 1]; + const right = numbers[middleIndex]; + return (left + right) / 2; + } + + const median = numbers[middleIndex]; return median; }