Skip to content
Closed
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
26 changes: 23 additions & 3 deletions Sprint-1/fix/median.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,29 @@
// 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;
// It must be an array
if (!Array.isArray(list)) {
return null;
}
// Keep only numeric values
const numbers = list.filter(
(value) => typeof value === "number" && !isNaN(value)
);

// If there are no numbers existing then return null
if (numbers.length === 0) return null;

// Sort numbers without modifying original list
const sorted = [...numbers].sort((a, b) => a - b);
Comment thread
cjyuan marked this conversation as resolved.
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.

Is it necessary to make a copy of numbers before sorting?

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.

No, it is not necessary to make a copy of numbers before sorting, however, it is a good practice.

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.

Can you elaborate how it is a good practice in this scenario?

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.

In this scenario it is not needed. I just tried to make it cleaner by removing non numeric values if any. Do you want me to remove it?

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.

"... to make it cleaner by removing non numeric values" -- You have already removed non numeric values using .filter().

You can keep the code unchanged. I am more interested in knowing why you think "making a copy of numbers before sorting" is a good practice. Can you explain?

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.

Ok. I got your point. According to me, making a copy before sorting is a good practice for the following reasons:

  1. We could accidentally modify it for example if we use the median function directly, the new file would be sorted and it would replace the original file
  2. Incase we need to refer the original file later in the code, we will not be able to since the index of the original file could get sorted
    I hope this answers. If i have missed anything, pl add to it. Thank you

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.

  • By "file", do you mean "array"?

  • It's true that numbers.sort() can mutate the numbers array. If we need to use numbers after sorting, then it is considered a safe practice to not mutate the array. In your implementation, is numbers being used after sorting?

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.

• Yes by file I meant array.
• No, in my current implementation code, the numbers array is not used again after the sorted variable is created.

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.

"immutability" do has its advantage. The reasons you gave do not quite fit the numbers array as the array is clearly not needed after sorting.

Thought you might be interested in this ChatGPT explaination:
https://chatgpt.com/share/69cf697a-5ea8-8331-bb33-47ccc8b02a17

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.

Ok. I will look at it in detail. Thank you

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

// For even length
if (sorted.length % 2 === 0) {
return (sorted[middle - 1] + sorted[middle]) / 2;
}

// For odd length
return sorted[middle];
}

module.exports = calculateMedian;
34 changes: 29 additions & 5 deletions Sprint-1/fix/median.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ describe("calculateMedian", () => {
{ input: [1, 2, 3, 4], expected: 2.5 },
{ input: [1, 2, 3, 4, 5, 6], expected: 3.5 },
].forEach(({ input, expected }) =>
it(`returns the median for [${input}]`, () => expect(calculateMedian(input)).toEqual(expected))
it(`returns the median for [${input}]`, () =>
expect(calculateMedian(input)).toEqual(expected))
);

[
Expand All @@ -24,17 +25,39 @@ describe("calculateMedian", () => {
{ input: [110, 20, 0], expected: 20 },
{ input: [6, -2, 2, 12, 14], expected: 6 },
].forEach(({ input, expected }) =>
it(`returns the correct median for unsorted array [${input}]`, () => expect(calculateMedian(input)).toEqual(expected))
it(`returns the correct median for unsorted array [${input}]`, () =>
expect(calculateMedian(input)).toEqual(expected))
);

it("doesn't modify the input array [3, 1, 2]", () => {
const list = [3, 1, 2];
calculateMedian(list);
expect(list).toEqual([3, 1, 2]);
});
// Test for single number array
it("returns the value for a single-element array", () => {
expect(calculateMedian([5])).toBe(5);
});
// Test for only 1 numeric value in an array
it("returns the only numeric value in mixed array", () => {
expect(calculateMedian(["apple", 10, "banana"])).toBe(10);
});
// Test for decimal numbers only
it("works with decimal numbers", () => {
expect(calculateMedian([2.5, 3.5, 4.5])).toBe(3.5);
});

[ 'not an array', 123, null, undefined, {}, [], ["apple", null, undefined] ].forEach(val =>
it(`returns null for non-numeric array (${val})`, () => expect(calculateMedian(val)).toBe(null))
[
"not an array",
123,
null,
undefined,
{},
[],
["apple", null, undefined],
].forEach((val) =>
it(`returns null for invalid input (${val})`, () =>
expect(calculateMedian(val)).toBe(null))
);

[
Expand All @@ -45,6 +68,7 @@ describe("calculateMedian", () => {
{ input: [3, "apple", 1, null, 2, undefined, 4], expected: 2.5 },
{ input: ["banana", 5, 3, "apple", 1, 4, 2], expected: 3 },
].forEach(({ input, expected }) =>
it(`filters out non-numeric values and calculates the median for [${input}]`, () => expect(calculateMedian(input)).toEqual(expected))
it(`filters out non-numeric values and calculates the median for [${input}]`, () =>
expect(calculateMedian(input)).toEqual(expected))
);
});
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) {
return [...new Set(arr)];
}
module.exports = dedupe;
19 changes: 18 additions & 1 deletion Sprint-1/implement/dedupe.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,29 @@ 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
test("returns copy of the original array if there are no duplicates", () => {
const input = [10, 45, 85, 20];
const result = dedupe(input);
expect(result).toEqual(input);
expect(input).toEqual([10, 45, 85, 20]);
expect(result).not.toBe(input);
Comment thread
cjyuan marked this conversation as resolved.
});
Comment thread
cjyuan marked this conversation as resolved.

// 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
test("returns first occurance for array of strings or numbers", () => {
expect(dedupe([10, 10, 20, 20, 30, 40])).toEqual([10, 20, 30, 40]);
expect(dedupe(["hello", "hello", "hi", "a", "hi"])).toEqual([
"hello",
"hi",
"a",
]);
});
11 changes: 10 additions & 1 deletion Sprint-1/implement/max.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
function findMax(elements) {
function findMax(arr) {
if (!Array.isArray(arr)) return -Infinity;

let max = -Infinity;
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] === "number" && arr[i] > max) {
max = arr[i];
}
}
return max;
}

module.exports = findMax;
33 changes: 32 additions & 1 deletion Sprint-1/implement/max.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,59 @@ 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([])).toBe(-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, returns that number", () => {
expect(findMax([5])).toBe(5);
});

// Given an array with both positive and negative numbers
// When passed to the max function
// Then it should return the largest number overall
test("returns the largest number overall", () => {
expect(findMax([-25, 3, 12, -32])).toBe(12);
});

// Given an array with just negative numbers
// When passed to the max function
// Then it should return the closest one to zero
test("returns the closest number to zero", () => {
expect(findMax([-25, -345, -1, -72])).toBe(-1);
});

// Given an array with decimal numbers
// When passed to the max function
// Then it should return the largest decimal number
test("returns the largest decimal number", () => {
expect(findMax([1.85, 2.563, 12.23, 0.24])).toBe(12.23);
});

// Given an array with non-number values
// When passed to the max function
// Then it should return the max and ignore non-numeric values
test("returns max and ignores non number values", () => {
expect(findMax(["stay", "300", "quiet", -32, 5])).toBe(5);
});

// 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
test("returns infinity in non number values", () => {
expect(findMax(["hi", "sally", "a", "alpha"])).toBe(-Infinity);
});
Comment thread
cjyuan marked this conversation as resolved.
// Given an array with null input
// returns -Infinity for null input
test("returns -Infinity where input is null", () => {
expect(findMax(null)).toBe(-Infinity);
});

// Given an array with undefined input
// returns -Infinity for undefined input
test("returns -Infinity where input is undefined", () => {
expect(findMax(undefined)).toBe(-Infinity);
});
12 changes: 11 additions & 1 deletion Sprint-1/implement/sum.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
function sum(elements) {
function sum(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] === "number" && !isNaN(arr[i])) {
total += arr[i];
}
}
return total;
}

let arr = [Infinity, -Infinity];
console.log(sum(arr));

module.exports = sum;
37 changes: 34 additions & 3 deletions Sprint-1/implement/sum.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,55 @@ const sum = require("./sum.js");
// Given an empty array
// When passed to the sum function
// Then it should return 0
test.todo("given an empty array, returns 0")
test("given an empty array, returns 0", () => {
expect(sum([])).toBe(0);
});

// Given an array with just one number
// When passed to the sum function
// Then it should return that number
test("returns the same number when an array has just 1 number", () => {
expect(sum([8])).toBe(8);
});

// Given an array containing negative numbers
// When passed to the sum function
// Then it should still return the correct total sum

test("given an array with negative numbers, returns correct sum", () => {
expect(sum([-50, -20, 10])).toBe(-60);
});
// Given an array with decimal/float numbers
// When passed to the sum function
// Then it should return the correct total sum

test("given an array with decimal/float numbers, returns correct sum", () => {
expect(sum([2.8, 4.2, 7.7])).toBeCloseTo(14.7);
});
Comment thread
cjyuan marked this conversation as resolved.
// Given an array containing non-number values
// When passed to the sum function
// Then it should ignore the non-numerical values and return the sum of the numerical elements
test("given an array with non number values, returns sum of numbers", () => {
expect(sum(["quiet", -20, "good", 10, 25])).toBe(15);
});

// Given an array with only non-number values
// When passed to the sum function
// Then it should return the least surprising value given how it behaves for all other inputs
test("returns 0 foe non number values", () => {
expect(sum(["sally", "cousin", "hi", "a"])).toBe(0);
});

// Given an array with NaN and numbers
// When passed to the sum function
// Then it should ignore NaN and return the sum of the numbers
test("should ignore NaN and return the correct sum", () => {
expect(sum([32, NaN, 25])).toEqual(57);
expect(sum([NaN, 1])).toEqual(1);
expect(sum([NaN, 0])).toEqual(0);
});

// Given an array with Infinity and -Infinity
// When passed to the sum function
// Then it should return NaN (standard JS behavior for infinite subtraction)
test("should return NaN when summing Infinity and -Infinity", () => {
expect(sum([Infinity, -Infinity])).toBeNaN();
});
3 changes: 1 addition & 2 deletions Sprint-1/refactor/includes.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
// Refactor the implementation of includes to use a for...of loop

function includes(list, target) {
for (let index = 0; index < list.length; index++) {
const element = list[index];
for (const element of list) {
if (element === target) {
return true;
}
Expand Down
Loading