From 22649fc1a98353101f5351b4f3abd5a3746d36dd Mon Sep 17 00:00:00 2001 From: KhotKeys Date: Fri, 7 Aug 2026 15:30:11 +0100 Subject: [PATCH] fix median function to handle unsorted arrays, non-numeric values and edge cases --- Sprint-1/fix/median.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Sprint-1/fix/median.js b/Sprint-1/fix/median.js index b22590bc6..6f73ace79 100644 --- a/Sprint-1/fix/median.js +++ b/Sprint-1/fix/median.js @@ -6,9 +6,12 @@ // or 'list' has mixed values (the function is expected to sort only numbers). function calculateMedian(list) { - const middleIndex = Math.floor(list.length / 2); - const median = list.splice(middleIndex, 1)[0]; - return median; + if (!Array.isArray(list)) return null; + const numbers = list.filter(n => typeof n === "number"); + 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 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; } module.exports = calculateMedian;