Skip to content
Closed
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
27 changes: 19 additions & 8 deletions Sprint-1/fix/median.js
Original file line number Diff line number Diff line change
@@ -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 (Number.isFinite(x)) {
numbers.push(x);
}
}
if (numbers.length === 0 || list.length === 0) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why check list.length?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to check for null value

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;
}

Expand Down
Loading