Skip to content
Open
Show file tree
Hide file tree
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
28 changes: 24 additions & 4 deletions Sprint-1/fix/median.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,30 @@
// 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).


function calculateMedian(list) {
const middleIndex = Math.floor(list.length / 2);
const median = list.splice(middleIndex, 1)[0];
return median;
// chekc it is an rray
if (!Array.isArray(list)) return null;

// pull out numbers
const nums = list.filter(n => typeof n === "number" && !Number.isNaN(n));

// If no numbers, return null
if (nums.length === 0) return null;

// Sort without changing original array
const sorted = [...nums].sort((a, b) => a - b);

const len = sorted.length;
const mid = Math.floor(len / 2);

// If length is odd, take middle element
if (len % 2 === 1) {
return sorted[mid];
}

// If length is even take average of two middle elements
return (sorted[mid - 1] + sorted[mid]) / 2;
}

module.exports = calculateMedian;
module.exports = calculateMedian;
5 changes: 4 additions & 1 deletion Sprint-1/implement/dedupe.js
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
function dedupe() {}
function dedupe(arr) {
// The spread operator [...] converts back to an array.
return [...new Set(arr)]; //New Set(arr) removes duplicates automatically
}
12 changes: 11 additions & 1 deletion Sprint-1/implement/max.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
function findMax(elements) {

function findMax(arr) {
// filter out non-numbers, non-numeric strings, and NaN. ALso convert string numbers to number
const numericValues = arr
.filter((item) => typeof item === "number" || (typeof item === "string" && item.trim() !== "" && !isNaN(item)))
.map((item) => Number(item));

// returns -Infinity i no numerical elements are found
if (numericValues.length === 0) return -Infinity;

return Math.max(...numericValues);
}

module.exports = findMax;
9 changes: 8 additions & 1 deletion Sprint-1/implement/sum.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
function sum(elements) {
sum.js
function sum(arr) {
return arr.reduce((accumulator, currentValue) => {
if (typeof currentValue === 'number' && !isNaN(currentValue)) { // investigate if the current element is a number and not NaN
return accumulator + currentValue;
}
return accumulator; // If not a number, return current sum
}, 0); // This line initialize sum at 0 for empty arrays
}

module.exports = sum;
Loading
Loading