Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 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
52 changes: 49 additions & 3 deletions Sprint-1/fix/median.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,56 @@
// 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 should not change the original array
//function should sort a copy of the array
//function should check if array has any non number values
//function should check if array has even number of integers or odd number before attempting to calculate median
//

function calculateMedian(list) {
const middleIndex = Math.floor(list.length / 2);
const median = list.splice(middleIndex, 1)[0];
return median;
//first we create an array and copy only numbers into it
//because we use array methods first we check we are passing an array
let numberArray = [];

function isNumber(value) {
if (typeof value === "number") {
return true;
}

return false;
}
Comment on lines +19 to +25
Copy link
Contributor

Choose a reason for hiding this comment

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

We could simplify

  if (condition)
    return true;
  return false;

into

  return condition;          // Note: Use !!(condition) if condition is not a Boolean-type value


function compareNumbers(a, b) {
return a - b;
}

if (Array.isArray(list)) {
//checking if we have been passed an array before picking numbers from any arrays
numberArray = list.filter(isNumber);
console.log(`new array ${numberArray}`);
} else {
return null;
}
Comment on lines +31 to +37
Copy link
Contributor

Choose a reason for hiding this comment

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

  1. Since the function will return immediately if list is not an array, we could simplify the code as:
  if (!Array.isArray(list)) return null;
  
  // no need else and no need to introduce {...} block
  ...
  

  1. It's best practice to keep the code clean by removing all the debugging code. Can you remove all the unnecessary console.log() statements?


numberArray.sort(compareNumbers); //sorting the copied array of numbers

//quickly check if the new array is empty which means there were no numbers in original array
if (numberArray.length === 0) {
return null;
}

let middleIndex = 0;
let middleIndexPlus1 = 0;

if (numberArray.length % 2 === 0) {
//if array has even number of items then a different median formula
middleIndex = Math.floor(numberArray.length / 2);
middleIndexPlus1 = middleIndex - 1;

return (numberArray[middleIndex] + numberArray[middleIndexPlus1]) / 2;
}
Comment on lines +46 to +55
Copy link
Contributor

Choose a reason for hiding this comment

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

If these two variables are used only inside the if block, it is better to declare them inside the block.


return numberArray.splice(Math.floor(numberArray.length / 2), 1)[0];
Copy link
Contributor

@cjyuan cjyuan Dec 2, 2025

Choose a reason for hiding this comment

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

Can you simplify this statement (line 57)?

}

module.exports = calculateMedian;
57 changes: 56 additions & 1 deletion Sprint-1/implement/dedupe.js
Original file line number Diff line number Diff line change
@@ -1 +1,56 @@
function dedupe() {}
function dedupe(myArray) {
//check array for duplicates
//for each item compare to all other items and return true if duplicate found
//if none return copy of array
function checkForDupe(item) {
let counter = 0;
for (let value of myArray) {
if (item === value) {
counter++;
}
}
if (counter > 1) {
return false;
} else {
return true;
}
}

const noDupeArray = myArray.filter(checkForDupe);

if (myArray.length === 0) {
//return empty array for empty array
return [];
} else if (myArray.length === noDupeArray.length) {
//return copy of array if no duplicates
return noDupeArray;
}

//to remove duplicates first we take a given item in an array
//and compare it to all the other items in the array.
//we will need a counter to keep track of the number of times an item matches
//we only want to keep items with a count of 1
//so for any matches with a count of 2 or more we remove the item at the matching index

myArray.forEach((item) => {
let matchCount = 0;

for (let i = 0; i < myArray.length; i++) {
if (item === myArray[i]) {
matchCount++;

if (matchCount > 1) {
myArray.splice(i, 1);
}
}
}
});

console.log(`my final array for duplicates is ${myArray}`);

return myArray;
}

dedupe(["ben", "two", "two", 2, "shine", "count", 9, "man"]);

module.exports = dedupe;
43 changes: 42 additions & 1 deletion Sprint-1/implement/dedupe.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,53 @@ E.g. dedupe([1, 2, 1]) target output: [1, 2]
// Given an empty array
// When passed to the dedupe function
// Then it should return an empty array
test.todo("given an empty array, it returns an empty array");
test("given an empty array, it returns an empty array", () => {
expect(dedupe([])).toEqual([]);
});

// Given an array with no duplicates
// When passed to the dedupe function
// Then it should return a copy of the original array
describe("returning copies of arrays with no duplicates", () => {
[
{ input: [1, 4, 5, 6, 2, 7, 8, 45], expected: [1, 4, 5, 6, 2, 7, 8, 45] },
{
input: [1, 3, 5, 7, 9, 15, 17, 19],
expected: [1, 3, 5, 7, 9, 15, 17, 19],
},
{
input: [1, 3, 50, 732, 987, 15000, 1790, 190],
expected: [1, 3, 50, 732, 987, 15000, 1790, 190],
},
{
input: ["one", "jim", 5, "messy", "tip", 15, "random", 19],
expected: ["one", "jim", 5, "messy", "tip", 15, "random", 19],
},
].forEach(({ input, expected }) =>
it("returns a copy of the original array for arrays with no duplicates", () =>
expect(dedupe(input)).toEqual(expected))
);
Comment on lines +42 to +44
Copy link
Contributor

Choose a reason for hiding this comment

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

The code on line 43 cannot check if expected is a copy of input. That is, it cannot check if expected and input are two different arrays with the same content.

});

// Given an array with strings or numbers
// When passed to the dedupe function
// Then it should remove the duplicate values, preserving the first occurence of each element
describe("removing duplicate values but keeping the first occurance of each element", () => {
[
{
input: [1, 2, 2, "cat", "dog", 9, "man", "cat"],
expected: [1, 2, "cat", "dog", 9, "man"],
},
{
input: ["ben", "two", "two", 2, "shine", "count", 9, "man"],
expected: ["ben", "two", 2, "shine", "count", 9, "man"],
},
{
input: ["ben", "two", "ben", 2, "ben", "ben", 2, "man", 2],
expected: ["ben", "two", 2, "man"],
},
].forEach(({ input, expected }) =>
it("removes any duplicate values from the array, keeping the first instance of each element", () =>
expect(dedupe(input)).toEqual(expected))
);
});
45 changes: 45 additions & 0 deletions Sprint-1/implement/max.js
Copy link
Contributor

Choose a reason for hiding this comment

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

This function has several bugs.

You may want to reimplement it following this approach:

  • First create a new array to keep only the values you consider "valid".
  • Then find the max in the new array.
    • When dealing with the elements in this new array, you don't have to check for invalid values.

Original file line number Diff line number Diff line change
@@ -1,4 +1,49 @@
function findMax(elements) {
if (elements.length === 0) {
return -Infinity;
} else if (elements.length === 1) {
return elements[0];
}

let largestNum = 0;
let largestValue = "";
let countNum = 0;

if (typeof elements[0] === "number") {
largestNum = elements[0];
} else {
let largestValue = elements[0];
}

for (let i = 1; i < elements.length; i++) {
if (typeof elements[i] === "number") {
countNum++;

if (elements[i] > largestNum) {
largestNum = elements[i];
}
} else {
if (elements[i] > largestValue) {
largestValue = elements[i];
}
}

//we create an array of numbers using filter
//if (typeof largestNum !== 'undefined') {

// numberArray = elements.filter((element) => typeof element === 'number');
// console.log(numberArray);

//}
}

if (countNum > 0) {
return largestNum;
} else {
return largestValue;
}
}

findMax(["zero", -4, -80, -100, -120, 0, "tom"]);

module.exports = findMax;
82 changes: 81 additions & 1 deletion Sprint-1/implement/max.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,108 @@ const findMax = require("./max.js");
// When passed to the max function
// Then it should return -Infinity
// Delete this test.todo and replace it with a test.
test.todo("given an empty array, returns -Infinity");
test("given an empty array, returns -Infinity", () =>
expect(findMax([])).toEqual(-Infinity));

// Given an array with one number
// When passed to the max function
// Then it should return that number
test("given an array with one number, it should return the number", () =>
expect(findMax([4])).toEqual(4));

// Given an array with both positive and negative numbers
// When passed to the max function
// Then it should return the largest number overall
describe("getting the largest number from an array of positive and negative numbers", () => {
[
{ input: [1, -4, -80, 100, -120, 0, 55], expected: 100 },
{ input: [20, 0, -80, 1, -10, -8, 5], expected: 20 },
{ input: [0, -4, -80, -100, -120, 0, -55], expected: 0 },
{ input: [17, -9, -400, 81, 120, 2, 5.5], expected: 120 },
{ input: [-1, -4, -70, 1000, -190, 1456, 0.5], expected: 1456 },
].forEach(({ input, expected }) =>
it(`returns the largest number overall`, () =>
expect(findMax(input)).toBe(expected))
);
});

// Given an array with just negative numbers
// When passed to the max function
// Then it should return the closest one to zero
describe("getting the largest number from an array of negative non-zero numbers", () => {
[
{ input: [-15, -4, -80, -100, -120, -7, -55], expected: -4 },
{ input: [-20, -90, -800, -11, -19, -8, -23], expected: -8 },
{
input: [-890, -6734, -89230, -1780, -128, -863927, -9076],
expected: -128,
},
{
input: [-1789, -1098, -1400, -1891, -1620, -2623, -3558],
expected: -1098,
},
{
input: [-1893, -490365, -709, -1000, -1790, -91456, -708],
expected: -708,
},
].forEach(({ input, expected }) =>
it(`returns the closest negative number to zero`, () =>
expect(findMax(input)).toBe(expected))
);
});

// Given an array with decimal numbers
// When passed to the max function
// Then it should return the largest decimal number
describe("getting the largest decimal number from an array of positive and negative numbers", () => {
[
{ input: [1.5, -4.8, -80.87, 1.09, -1.2, 0.967, 5.95], expected: 5.95 },
{ input: [2.0, 9.7, -20.801, 21.7, -10.9, 3.768, 56.4], expected: 56.4 },
{ input: [0.345, 8.876, 9.56, 34.2, 32.4, 32.212, 31.989], expected: 34.2 },
{ input: [5.5, 7.685, 7.865, 7.6854, 7.6853, 7.6855], expected: 7.865 },
{ input: [-5.674, 9.1, 9.121, 9.122, 9.1221, 9.12213], expected: 9.12213 },
].forEach(({ input, expected }) =>
it(`returns the largest number overall`, () =>
expect(findMax(input)).toBe(expected))
);
});

// Given an array with non-number values
// When passed to the max function
// Then it should return the max and ignore non-numeric values
describe("returning the max number from array with numeric and non-numeric values", () => {
[
{
input: [1.5, -4.8, "ten", 1.09, "fifty six", 0.967, "six"],
expected: 1.5,
},
{ input: ["twenty", "ben", "x-ray", 23, -10, "joe", 5], expected: 23 },
{ input: ["zero", -4, -80, -100, -120, 0, "tom"], expected: 0 },
].forEach(({ input, expected }) =>
it(`returns the largest number ignoring non-numeric values`, () =>
expect(findMax(input)).toEqual(expected))
);
});

// Given an array with only non-number values
// When passed to the max function
// Then it should return the least surprising value given how it behaves for all other inputs
describe("returning the max number from array with numeric and non-numeric values", () => {
[
{
input: ["dam", "meat", "ten", "faster", "fifty six", "loud", "mix"],
expected: "ten",
},
{
input: ["twenty", "ben", "x-ray", "king", "clive", "joe", "oxen"],
expected: "x-ray",
},
{
input: ["zero", "switch", "price", "tom", "max", "nick", "reach"],
expected: "tom",
},
].forEach(({ input, expected }) =>
it(`returns the largest number ignoring non-numeric values`, () =>
expect(findMax(input)).toEqual(expected))
);
});
Comment on lines +105 to +123
Copy link
Contributor

Choose a reason for hiding this comment

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

How do you determine "max" value among non-number values?

What return value do you expect from the following function calls?

findMax( ["Ten", "one"] );
findMax( ["Ten", null] );
findMax( ["Ten", true] );
findMax( ["2", "1000"] );
findMax( [undefined, [1,2,3,4] ] );

53 changes: 53 additions & 0 deletions Sprint-1/implement/sum.js
Copy link
Contributor

Choose a reason for hiding this comment

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

I have to praise you for going through a great length to implement a sum() function that takes into consideration the number of decimal places in the input array.

Original file line number Diff line number Diff line change
@@ -1,4 +1,57 @@
function sum(elements) {
//function to check the number of decimal places
function numberOfFloat(number) {
if (Number.isInteger(number)) {
return 0;
} else {
return number.toString().split(".")[1].length;
}
}
Comment on lines +3 to +9
Copy link
Contributor

Choose a reason for hiding this comment

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

This approach to figure out number of decimal places does not work for all floating point numbers.

  • Some floating point numbers can also be represented in scientific format. For examples, 1e-100, 3.12e50.


function largestFloat(array) {
let largestNum = 0;
let floatValue = 0;
for (number of array) {
floatValue = numberOfFloat(number);

if (floatValue > largestNum) {
largestNum = floatValue;
}
}

return largestNum;
}

const initialValue = 0;

const numberArray = elements.filter((element) => typeof element === "number");

const checkIfFloat = largestFloat(numberArray);

if (elements.length === 0) {
return 0;
}

if (numberArray.length > 0) {
const totalSum = numberArray.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue
);

if (checkIfFloat === 0) {
return totalSum;
} else {
return Number(totalSum.toFixed(checkIfFloat));
}
} else {
const returnValue = elements.reduce(
(accumulator, currentValue) => accumulator + currentValue
);

return returnValue;
}
}

sum([-34.6, 1.87, 10.67, -7.984, 15.5, -1.1, 8.0]);

module.exports = sum;
Loading