Skip to content

Commit c0e150e

Browse files
committed
fix the list is not iterable issue - so i check if the list is iterable or not and do some cleaning -only left the comment i needed
1 parent f1b988e commit c0e150e

1 file changed

Lines changed: 11 additions & 18 deletions

File tree

‎Sprint-1/fix/median.js‎

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,26 @@
1-
// Fix this implementation
2-
// Start by running the tests for this function
3-
// If you're in the Sprint-1 directory, you can run `npm test -- fix` to run the tests in the fix directory
4-
5-
// Hint: Please consider scenarios when 'list' doesn't have numbers (the function is expected to return null)
6-
// or 'list' has mixed values (the function is expected to sort only numbers).
7-
81
function calculateMedian(list) {
9-
// Filter out non-numeric values
10-
// const numbers = list.filter((x) => typeof x === "number");
11-
const numbers = [];
12-
for (const x of list) {
13-
if (Number.isFinite(x)) {
14-
numbers.push(x);
15-
}
2+
//Return null if list is null/undefined or not iterable
3+
if (!list || typeof list[Symbol.iterator] !== "function") {
4+
return null;
165
}
6+
const numbers = Array.from(list).filter(Number.isFinite);
7+
178
if (numbers.length === 0) {
189
return null;
1910
}
20-
// Sort the numbers
11+
2112
numbers.sort((a, b) => a - b);
13+
2214
const middleIndex = Math.floor(numbers.length / 2);
23-
// for even length arrays
15+
16+
// 5. Calculate median for even-length arrays
2417
if (numbers.length % 2 === 0) {
2518
const left = numbers[middleIndex - 1];
2619
const right = numbers[middleIndex];
2720
return (left + right) / 2;
2821
}
2922

30-
const median = numbers[middleIndex];
31-
return median;
23+
// 6. Calculate median for odd-length arrays
24+
return numbers[middleIndex];
3225
}
3326
module.exports = calculateMedian;

0 commit comments

Comments
 (0)