Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions Sprint-1/fix/median.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,33 @@
// 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;
// Return null immediately if the input is not an array
if (!Array.isArray(list)) {
return null;
}

// Keep only real numeric values
const numbersOnly = list.filter(
(item) => typeof item === "number" && !Number.isNaN(item)
);

// Return null if the array contains no numbers
if (numbersOnly.length === 0) {
return null;
}

// Create a sorted copy so the original input is not changed
const sortedNumbers = [...numbersOnly].sort((a, b) => a - b);

const middleIndex = Math.floor(sortedNumbers.length / 2);

// For an even-length array, median is the average of the two middle values
if (sortedNumbers.length % 2 === 0) {
return (sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2;
}

// For an odd-length array, median is the middle value
return sortedNumbers[middleIndex];
}

module.exports = calculateMedian;
Loading