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
23 changes: 20 additions & 3 deletions Sprint-1/fix/median.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,26 @@
// 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;
// validate input
if (!Array.isArray(list)) return null;

// keep only finite numbers (ignore numeric strings and other types)
const numbers = list.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
if (numbers.length === 0) return null;

// sort numerically (we can sort the filtered array in-place)
numbers.sort((a, b) => a - b);

const n = numbers.length;
const mid = Math.floor(n / 2);

// odd length -> return middle element
if (n % 2 === 1) return numbers[mid];

// even length -> average of two middle values
return (numbers[mid - 1] + numbers[mid]) / 2;
}

module.exports = calculateMedian;
21 changes: 20 additions & 1 deletion Sprint-1/implement/dedupe.js
Original file line number Diff line number Diff line change
@@ -1 +1,20 @@
function dedupe() {}
// Remove duplicate primitive values from an array while preserving
// the first occurrence order. Does not mutate the input array.
function dedupe(list) {
// Defensive: if input is not an array, return an empty array
if (!Array.isArray(list)) return [];

const seen = new Set();
const out = [];

for (const item of list) {
if (!seen.has(item)) {
seen.add(item);
out.push(item);
}
}

return out;
}

module.exports = dedupe;
25 changes: 23 additions & 2 deletions Sprint-1/implement/dedupe.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,34 @@ E.g. dedupe([1, 2, 1]) returns [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([]);
});

test("array with no duplicates returns a copy", () => {
const arr = [1, 2, 3];
const out = dedupe(arr);
expect(out).toEqual(arr);
expect(out).not.toBe(arr); // should be a new array
});
Comment on lines +23 to +28
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.

There is a chance that, even though out has incorrect elements (for example, []),
the two tests on lines 27-28 could still pass. Can you figure out why, and then fix the tests accordingly?


test("removes duplicates while preserving first occurrence order", () => {
const input = [5, 1, 1, 2, 3, 2, 5, 8];
expect(dedupe(input)).toEqual([5, 1, 2, 3, 8]);
});

test("does not mutate the original array", () => {
const arr = ["a", "a", "b"];
const copy = arr.slice();
dedupe(arr);
expect(arr).toEqual(copy);
});

// Given an array with no duplicates
// When passed to the dedupe function
// Then it should return a copy of the original array

// Given an array of strings or numbers
// When passed to the dedupe function
// Then it should return a new array with duplicates removed while preserving the
// Then it should return a new array with duplicates removed while preserving the
// first occurrence of each element from the original array.
14 changes: 14 additions & 0 deletions Sprint-1/implement/max.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
function findMax(elements) {
if (!Array.isArray(elements)) return -Infinity;

// Keep only finite numbers
const numbers = elements.filter(
(x) => typeof x === "number" && Number.isFinite(x)
);
if (numbers.length === 0) return -Infinity;

// Find max without mutating the input
let max = -Infinity;
for (const n of numbers) {
if (n > max) max = n;
}
return max;
}

module.exports = findMax;
23 changes: 21 additions & 2 deletions Sprint-1/implement/max.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,47 @@ 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([42])).toBe(42);
});

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

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

// Given an array with decimal numbers
// When passed to the max function
// Then it should return the largest decimal number

test("given an array with decimal numbers, returns the largest decimal number", () => {
expect(findMax([1.5, 2.3, 0.7])).toBe(2.3);
});
// 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("given an array with non-number values, returns the max and ignores non-numeric values", () => {
expect(findMax(["hey", 10, "hi", 60, 10])).toBe(60);
});

// 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("given an array with only non-number values, returns -Infinity", () => {
expect(findMax(["hey", "hi", "there"])).toBe(-Infinity);
});
Comment on lines +53 to +62
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.

When a string representing a valid numeric literal (for example, "300") is compared to a number,
JavaScript first converts the string into its numeric equivalent before performing the comparison.
As a result, the expression 20 < "300" evaluates to true.

To test if the function can correctly ignore non-numeric values,
consider including a string such as "300" in the relevant test cases.

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.

Thanks. I'll add a test that includes a numeric-looking string("300") to ensure those strings are ignored, and implement findMax to only consider real number values.

9 changes: 9 additions & 0 deletions Sprint-1/implement/sum.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
function sum(elements) {
if (!Array.isArray(elements)) return 0;

let total = 0;
for (const el of elements) {
if (typeof el === "number") {
total += el;
}
}
Comment on lines +5 to +9
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.

What do you expect from the following function calls (on extreme cases)?
Does your function return the value you expected?

sum([NaN, 1]);
sum([Infinity, -Infinity]);

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.

Thanks - great question. I chose to ignore non finite values so the function only adds finite numbers. That means:
sum[NaN, 1] -> 1
sum [Infinity, -Infinity]) -> 0

return total;
}

module.exports = sum;
26 changes: 24 additions & 2 deletions Sprint-1/implement/sum.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,46 @@ 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("given an array with one number, returns that number", () => {
expect(sum([42])).toBe(42);
});

// Given an array with multiple numbers
// When passed to the sum function
// Then it should return the total sum of those numbers
test("given an array with multiple numbers, returns the correct sum", () => {
expect(sum([10, 20, 30])).toBe(60);
});
// 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 the correct sum", () => {
expect(sum([-10, 20, -5])).toBe(5);
});
// 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 numbers, returns the correct sum", () => {
expect(sum([1.5, 2.5, 3.5])).toBe(7.5);
});
Comment on lines +42 to +44
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.

Decimal numbers in most programming languages (including JS) are internally represented in "floating point number" format. Floating point arithmetic is not exact. For example, the result of 46.5678 - 46 === 0.5678 is false because 46.5678 - 46 only yield a value that is very close to 0.5678. Even changing the order in which the program add/subtract numbers can yield different values.

So the following could happen

  expect( 1.2 + 0.6 + 0.005 ).toEqual( 1.805 );                // This fail
  expect( 1.2 + 0.6 + 0.005 ).toEqual( 1.8049999999999997 );   // This pass
  expect( 0.005 + 0.6 + 1.2 ).toEqual( 1.8049999999999997 );   // This fail

  console.log(1.2 + 0.6 + 0.005 == 1.805);  // false
  console.log(1.2 + 0.6 + 0.005 == 0.005 + 0.6 + 1.2); // false

Can you find a more appropriate way to test a value (that involves decimal number calculations) for equality?

Suggestion: Look up

  • Checking equality in floating point arithmetic in JavaScript
  • Checking equality in floating point arithmetic with Jest


// 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 containing non-number values, returns the correct sum", () => {
expect(sum(["hey", 10, "hi", 60, 10])).toBe(80);
});

// 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("given an array with only non-number values, returns 0", () => {
expect(sum(["hey", "hi", "there"])).toBe(0);
});
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
32 changes: 32 additions & 0 deletions Sprint-1/stretch/aoc-2018-day1/solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const fs = require("fs");
const path = require("path");

// Read input relative to this file so script can be run from anywhere
const data = fs.readFileSync(path.join(__dirname, "input.txt"), "utf8");
const changes = data
.split(/\r?\n/)
.map((s) => s.trim())
.filter(Boolean)
.map(Number);

// Part 1: final frequency after one pass
const finalFrequency = changes.reduce((acc, change) => acc + change, 0);

// Part 2: first repeated cumulative frequency (iterate the list repeatedly)
function findFirstDuplicate(arr) {
const seen = new Set([0]);
let freq = 0;

while (true) {
for (const change of arr) {
freq += change;
if (seen.has(freq)) return freq;
seen.add(freq);
}
}
}

const firstDuplicate = findFirstDuplicate(changes);

console.log("Final frequency (part 1):", finalFrequency);
console.log("First repeated frequency (part 2):", firstDuplicate);
Loading