Skip to content

Commit 31bcc22

Browse files
committed
Fix: Remove unnecessary spread before sorting in calculateMedian
1 parent f9f7dc0 commit 31bcc22

1 file changed

Lines changed: 6 additions & 3 deletions

File tree

Sprint-1/fix/median.js

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,13 @@ function calculateMedian(list) {
1212
const nums = list.filter((x) => typeof x === "number" && isFinite(x));
1313
// Return null if no valid numbers remain
1414
if (nums.length === 0) return null;
15-
16-
const sorted = [...nums].sort((a, b) => a - b);
15+
// Sort the numbers in ascending order
16+
// filter already returns a new array so need to spread before spreading
17+
const sorted = nums.sort((a, b) => a - b);
18+
// Find the middle index of the sorted array
1719
const middleIndex = Math.floor(sorted.length / 2);
18-
20+
// If odd length, return the middle index
21+
// If even length, return the average of the two middle elements
1922
return sorted.length % 2 !== 0
2023
? sorted[middleIndex]
2124
: (sorted[middleIndex - 1] + sorted[middleIndex]) / 2;

0 commit comments

Comments
 (0)