diff --git a/Sprint-1/fix/median.js b/Sprint-1/fix/median.js index b22590bc6..db759d5ba 100644 --- a/Sprint-1/fix/median.js +++ b/Sprint-1/fix/median.js @@ -6,9 +6,31 @@ // 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: must be an array + if (!Array.isArray(list)) { + return null; + } + + // Filter out non-numeric values + const numbers = list.filter((item) => typeof item === "number"); + + // If no numeric values, return null + if (numbers.length === 0) { + return null; + } + + // Sort numbers without mutating original list + const sorted = [...numbers].sort((a, b) => a - b); + + const middleIndex = Math.floor(sorted.length / 2); + + // Odd length → return middle number + if (sorted.length % 2 !== 0) { + return sorted[middleIndex]; + } + + // Even length → average of two middle numbers + return (sorted[middleIndex - 1] + sorted[middleIndex]) / 2; } module.exports = calculateMedian; diff --git a/Sprint-1/implement/dedupe.js b/Sprint-1/implement/dedupe.js index 781e8718a..209465014 100644 --- a/Sprint-1/implement/dedupe.js +++ b/Sprint-1/implement/dedupe.js @@ -1 +1,5 @@ -function dedupe() {} +function dedupe(arr) { + return [...new Set(arr)]; +} + +module.exports = dedupe; \ No newline at end of file diff --git a/Sprint-1/implement/max.js b/Sprint-1/implement/max.js index 6dd76378e..ceacf7c5a 100644 --- a/Sprint-1/implement/max.js +++ b/Sprint-1/implement/max.js @@ -1,4 +1,9 @@ function findMax(elements) { + const numbers = elements.filter((item) => typeof item === "number"); + if (numbers.length === 0) { + return -Infinity; + } + return Math.max(...numbers); } module.exports = findMax; diff --git a/Sprint-1/implement/max.test.js b/Sprint-1/implement/max.test.js index 82f18fd88..ebfabf0fa 100644 --- a/Sprint-1/implement/max.test.js +++ b/Sprint-1/implement/max.test.js @@ -16,28 +16,49 @@ 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.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 positive and negative numbers, returns the largest", () => { + expect(findMax([-10, 5, 3, -2])).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 only negative numbers, returns the closest to zero", () => { + expect(findMax([-10, -3, -20])).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", () => { + expect(findMax([1.2, 3.5, 2.8])).toBe(3.5); +}); // 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, ignores them and returns the max", () => { + 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(['a', 'b', null, undefined])).toBe(-Infinity); +}); \ No newline at end of file diff --git a/Sprint-1/implement/sum.js b/Sprint-1/implement/sum.js index 9062aafe3..7d4ec4186 100644 --- a/Sprint-1/implement/sum.js +++ b/Sprint-1/implement/sum.js @@ -1,4 +1,9 @@ function sum(elements) { + const numbers = elements.filter((item) => typeof item === "number"); + if (numbers.length === 0) { + return 0; + } + return numbers.reduce((total, num) => total + num, 0); } module.exports = sum; diff --git a/Sprint-1/implement/sum.test.js b/Sprint-1/implement/sum.test.js index dd0a090ca..32bab4ade 100644 --- a/Sprint-1/implement/sum.test.js +++ b/Sprint-1/implement/sum.test.js @@ -13,24 +13,42 @@ 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.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 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 total", () => { + expect(sum([-5, 10, -3])).toBe(2); +}); // 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 total", () => { + expect(sum([1.5, 2.5, 3.1])).toBe(7.1); +}); // 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, ignores them and returns the sum of numbers", () => { + 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(["a", null, undefined, "b"])).toBe(0); +}); diff --git a/Sprint-1/refactor/includes.js b/Sprint-1/refactor/includes.js index 29dad81f0..8c9ae2e66 100644 --- a/Sprint-1/refactor/includes.js +++ b/Sprint-1/refactor/includes.js @@ -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; } diff --git a/Sprint-2/debug/address.js b/Sprint-2/debug/address.js index 940a6af83..a3f63cd92 100644 --- a/Sprint-2/debug/address.js +++ b/Sprint-2/debug/address.js @@ -4,6 +4,19 @@ // but it isn't working... // Fix anything that isn't working +/*const address = { + houseNumber: 42, + street: "Imaginary Road", + city: "Manchester", + country: "England", + postcode: "XYZ 123", +}; + +console.log(`My house number is ${address[0]}`); */ + +// The line "address[0]" is wrong. Because address is an object not an array, so "address[0]" is undefined. The output will be "My house number is undefined". + +// Corrected code const address = { houseNumber: 42, street: "Imaginary Road", @@ -12,4 +25,4 @@ const address = { postcode: "XYZ 123", }; -console.log(`My house number is ${address[0]}`); +console.log(`My house number is ${address.houseNumber}`); \ No newline at end of file diff --git a/Sprint-2/debug/author.js b/Sprint-2/debug/author.js index 8c2125977..37a05131d 100644 --- a/Sprint-2/debug/author.js +++ b/Sprint-2/debug/author.js @@ -3,7 +3,7 @@ // This program attempts to log out all the property values in the object. // But it isn't working. Explain why first and then fix the problem -const author = { +/* const author = { firstName: "Zadie", lastName: "Smith", occupation: "writer", @@ -14,3 +14,21 @@ const author = { for (const value of author) { console.log(value); } +*/ + +// Prediction and Explanation +/* The line "for (const value of author) {console.log(value);}" will not work because for-of is used only for iterable things, e.g: arrays, strings, maps, sets. +But author is a plain object (created with {}), and plain objects are not iterable. So Javascript throws: TypeError: author is not iterable because objects don't have a natural order to loop through. */ + +// Corrected code +const author = { + firstName: "Zadie", + lastName: "Smith", + occupation: "writer", + age: 40, + alive: true, +}; + +for (const value of Object.values(author)) { + console.log(value); +} diff --git a/Sprint-2/debug/recipe.js b/Sprint-2/debug/recipe.js index 6cbdd22cd..ab5c9d0cd 100644 --- a/Sprint-2/debug/recipe.js +++ b/Sprint-2/debug/recipe.js @@ -4,7 +4,7 @@ // Each ingredient should be logged on a new line // How can you fix it? -const recipe = { +/*const recipe = { title: "bruschetta", serves: 2, ingredients: ["olive oil", "tomatoes", "salt", "pepper"], @@ -13,3 +13,26 @@ const recipe = { console.log(`${recipe.title} serves ${recipe.serves} ingredients: ${recipe}`); +*/ + +// Prediction and Explanation +/* +The line inside the template string: ${recipe} does not print the ingredients. +Instead, JavaScript converts the entire recipe object into a string, which becomes "[object Object]". This happens +because plain objects {} are not automatically converted into readable text. The program should print each ingredient on a new line, but the current code +never loops through recipe.ingredients, so nothing is printed correctly. +*/ + +// Corrected code +const recipe = { + title: "bruschetta", + serves: 2, + ingredients: ["olive oil", "tomatoes", "salt", "pepper"], +}; + +console.log(`${recipe.title} serves ${recipe.serves} +ingredients:`); + +for (const ingredient of recipe.ingredients) { + console.log(ingredient); +} diff --git a/Sprint-2/implement/contains.js b/Sprint-2/implement/contains.js index cd779308a..05f18e140 100644 --- a/Sprint-2/implement/contains.js +++ b/Sprint-2/implement/contains.js @@ -1,3 +1,10 @@ -function contains() {} +function contains(obj, prop) { + if (typeof obj !== "object" || obj === null || Array.isArray(obj)) { + return false; + } + + return obj.hasOwnProperty(prop); +} module.exports = contains; + diff --git a/Sprint-2/implement/contains.test.js b/Sprint-2/implement/contains.test.js index 326bdb1f2..9a232aa56 100644 --- a/Sprint-2/implement/contains.test.js +++ b/Sprint-2/implement/contains.test.js @@ -16,20 +16,47 @@ as the object doesn't contains a key of 'c' // Given a contains function // When passed an object and a property name // Then it should return true if the object contains the property, false otherwise +test("returns true when object contains the property", () => { + const obj = { a: 1, b: 2 }; + expect(contains(obj, "a")).toBe(true); +}); + +test("returns false when object does not contain the property", () => { + const obj = { a: 1, b: 2 }; + expect(contains(obj, "c")).toBe(false); +}); + // Given an empty object // When passed to contains // Then it should return false -test.todo("contains on empty object returns false"); +// test.todo("contains on empty object returns false"); +test("contains on empty object returns false", () => { + expect(contains({}, "a")).toBe(false); +}); // Given an object with properties // When passed to contains with an existing property name // Then it should return true +test("returns true when object contains the property", () => { + const obj = { a: 1, b: 2 }; + expect(contains(obj, "a")).toBe(true); +}); // Given an object with properties // When passed to contains with a non-existent property name // Then it should return false +test("returns false when object does not contain the property", () => { + const obj = { a: 1, b: 2 }; + expect(contains(obj, "c")).toBe(false); +}); // Given invalid parameters like an array // When passed to contains // Then it should return false or throw an error +test("returns false for invalid parameters like an array", () => { + expect(contains([], "a")).toBe(false); + expect(contains(null, "a")).toBe(false); + expect(contains(123, "a")).toBe(false); + expect(contains("hello", "a")).toBe(false); +}); diff --git a/Sprint-2/interpret/invert.js b/Sprint-2/interpret/invert.js index bb353fb1f..48466c281 100644 --- a/Sprint-2/interpret/invert.js +++ b/Sprint-2/interpret/invert.js @@ -5,7 +5,7 @@ // Then it should swap the keys and values in the object // E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"} - +/* function invert(obj) { const invertedObj = {}; @@ -15,15 +15,31 @@ function invert(obj) { return invertedObj; } + */ -// a) What is the current return value when invert is called with { a : 1 } +// a) What is the current return value when invert is called with { a : 1 } - The current return value is { key: 1} -// b) What is the current return value when invert is called with { a: 1, b: 2 } +// b) What is the current return value when invert is called with { a: 1, b: 2 } - The current return value is { key: 2} -// c) What is the target return value when invert is called with {a : 1, b: 2} +// c) What is the target return value when invert is called with {a : 1, b: 2} - The target return value is { "1": "a", "2": "b" } // c) What does Object.entries return? Why is it needed in this program? +/* Object.entries(obj) returns an array of [key, value] pairs. Example: Object.entries({ a:1, b:2 }) returns [["a", 1], ["b", 2]]. +It is needed because the loop "for (const [key, value] of Object.entries(obj))" let's each pair destructure easily. +*/ -// d) Explain why the current return value is different from the target output +// d) Explain why the current return value is different from the target output - It is because this line "invertedObj.key = value;" uses literal string "key instead of the variable key" which is a wrong property name, +// instead of this "invertedObj[value] = key;" // e) Fix the implementation of invert (and write tests to prove it's fixed!) +function invert(obj) { + const invertedObj = {}; + + for (const [key, value] of Object.entries(obj)) { + invertedObj[value] = key; + } + + return invertedObj; +} + +module.exports = invert; diff --git a/Sprint-2/interpret/invert.test.js b/Sprint-2/interpret/invert.test.js new file mode 100644 index 000000000..f8643a570 --- /dev/null +++ b/Sprint-2/interpret/invert.test.js @@ -0,0 +1,17 @@ +const invert = require("./invert.js"); + +test("inverts a single key-value pair", () => { + expect(invert({ a: 1 })).toEqual({ 1: "a" }); +}); + +test("inverts multiple key-value pairs", () => { + expect(invert({ a: 1, b: 2 })).toEqual({ 1: "a", 2: "b" }); +}); + +test("handles empty objects", () => { + expect(invert({})).toEqual({}); +}); + +test("handles string values", () => { + expect(invert({ x: "hello" })).toEqual({ hello: "x" }); +}); diff --git a/Sprint-3/todo-list/index.html b/Sprint-3/todo-list/index.html index 4d12c4654..784a4bd4c 100644 --- a/Sprint-3/todo-list/index.html +++ b/Sprint-3/todo-list/index.html @@ -1,40 +1,51 @@ - + - - - - ToDo List - - + + + + ToDo List + + - - - -
-

My ToDo List

+ + + +
+

My ToDo List

-
- - -
+
+ + + +
- + - - - -
- + +
+ diff --git a/Sprint-3/todo-list/script.mjs b/Sprint-3/todo-list/script.mjs index ba0b2ceae..a804b4c69 100644 --- a/Sprint-3/todo-list/script.mjs +++ b/Sprint-3/todo-list/script.mjs @@ -1,4 +1,4 @@ -// Store everything imported from './todos.mjs' module as properties of an object named Todos +// Store everything imported from './todos.mjs' module as properties of an object named Todos import * as Todos from "./todos.mjs"; // To store the todo tasks @@ -7,16 +7,23 @@ const todos = []; // Set up tasks to be performed once on page load window.addEventListener("load", () => { document.getElementById("add-task-btn").addEventListener("click", addNewTodo); + document + .getElementById("delete-completed-btn") + .addEventListener("click", () => { + const updated = Todos.deleteCompleted(todos); + todos.length = 0; + todos.push(...updated); + render(); + }); // Populate sample data - Todos.addTask(todos, "Wash the dishes", false); + Todos.addTask(todos, "Wash the dishes", false); Todos.addTask(todos, "Do the shopping", true); render(); }); - -// A callback that reads the task description from an input field and +// A callback that reads the task description from an input field and // append a new task to the todo list. function addNewTodo() { const taskInput = document.getElementById("new-task-input"); @@ -45,12 +52,11 @@ function render() { }); } - // Note: // - First child of #todo-item-template is a
  • element. // We will create each ToDo list item as a clone of this node. // - This variable is declared here to be close to the only function that uses it. -const todoListItemTemplate = +const todoListItemTemplate = document.getElementById("todo-item-template").content.firstElementChild; // Create a
  • element for the given todo task @@ -62,15 +68,15 @@ function createListItem(todo, index) { li.classList.add("completed"); } - li.querySelector('.complete-btn').addEventListener("click", () => { + li.querySelector(".complete-btn").addEventListener("click", () => { Todos.toggleCompletedOnTask(todos, index); render(); }); - - li.querySelector('.delete-btn').addEventListener("click", () => { + + li.querySelector(".delete-btn").addEventListener("click", () => { Todos.deleteTask(todos, index); render(); }); return li; -} \ No newline at end of file +} diff --git a/Sprint-3/todo-list/todos.mjs b/Sprint-3/todo-list/todos.mjs index f17ab6a25..08371b71e 100644 --- a/Sprint-3/todo-list/todos.mjs +++ b/Sprint-3/todo-list/todos.mjs @@ -26,4 +26,9 @@ export function toggleCompletedOnTask(todos, taskIndex) { if (todos[taskIndex]) { todos[taskIndex].completed = !todos[taskIndex].completed; } -} \ No newline at end of file +} + +// Delete all tasks that are completed +export function deleteCompleted(todos) { + return todos.filter((todo) => !todo.completed); +} diff --git a/Sprint-3/todo-list/todos.test.mjs b/Sprint-3/todo-list/todos.test.mjs index bae7ae491..7b6acf3b4 100644 --- a/Sprint-3/todo-list/todos.test.mjs +++ b/Sprint-3/todo-list/todos.test.mjs @@ -13,7 +13,7 @@ function createMockTodos() { { task: "Task 1 description", completed: true }, { task: "Task 2 description", completed: false }, { task: "Task 3 description", completed: true }, - { task: "Task 4 description", completed: false }, + { task: "Task 4 description", completed: false }, ]; } @@ -29,7 +29,6 @@ describe("addTask()", () => { }); test("Should append a new task to the end of a ToDo list", () => { - const todos = createMockTodos(); const lengthBeforeAddition = todos.length; Todos.addTask(todos, theTask.task, theTask.completed); @@ -42,7 +41,6 @@ describe("addTask()", () => { }); describe("deleteTask()", () => { - test("Delete the first task", () => { const todos = createMockTodos(); const todosBeforeDeletion = createMockTodos(); @@ -53,7 +51,7 @@ describe("deleteTask()", () => { expect(todos[0]).toEqual(todosBeforeDeletion[1]); expect(todos[1]).toEqual(todosBeforeDeletion[2]); - expect(todos[2]).toEqual(todosBeforeDeletion[3]); + expect(todos[2]).toEqual(todosBeforeDeletion[3]); }); test("Delete the second task (a middle task)", () => { @@ -66,7 +64,7 @@ describe("deleteTask()", () => { expect(todos[0]).toEqual(todosBeforeDeletion[0]); expect(todos[1]).toEqual(todosBeforeDeletion[2]); - expect(todos[2]).toEqual(todosBeforeDeletion[3]); + expect(todos[2]).toEqual(todosBeforeDeletion[3]); }); test("Delete the last task", () => { @@ -79,7 +77,7 @@ describe("deleteTask()", () => { expect(todos[0]).toEqual(todosBeforeDeletion[0]); expect(todos[1]).toEqual(todosBeforeDeletion[1]); - expect(todos[2]).toEqual(todosBeforeDeletion[2]); + expect(todos[2]).toEqual(todosBeforeDeletion[2]); }); test("Delete a non-existing task", () => { @@ -94,7 +92,6 @@ describe("deleteTask()", () => { }); describe("toggleCompletedOnTask()", () => { - test("Expect the 'completed' property to toggle on an existing task", () => { const todos = createMockTodos(); const taskIndex = 1; @@ -111,13 +108,12 @@ describe("toggleCompletedOnTask()", () => { const todos = createMockTodos(); const todosBeforeToggle = createMockTodos(); Todos.toggleCompletedOnTask(todos, 1); - - expect(todos[0]).toEqual(todosBeforeToggle[0]); + + expect(todos[0]).toEqual(todosBeforeToggle[0]); expect(todos[2]).toEqual(todosBeforeToggle[2]); expect(todos[3]).toEqual(todosBeforeToggle[3]); }); - test("Expect no change when toggling on a non-existing task", () => { const todos = createMockTodos(); const todosBeforeToggle = createMockTodos(); @@ -130,3 +126,39 @@ describe("toggleCompletedOnTask()", () => { }); }); +describe("deleteCompleted()", () => { + test("Should remove all completed tasks", () => { + const todos = createMockTodos(); + + // Run + const result = Todos.deleteCompleted(todos); + + // Only tasks with completed: false should remain + expect(result).toEqual([ + { task: "Task 2 description", completed: false }, + { task: "Task 4 description", completed: false }, + ]); + }); + + test("Should return an empty array if all tasks are completed", () => { + const todos = [ + { task: "A", completed: true }, + { task: "B", completed: true }, + ]; + + const result = Todos.deleteCompleted(todos); + + expect(result).toEqual([]); + }); + + test("Should return the same array if no tasks are completed", () => { + const todos = [ + { task: "A", completed: false }, + { task: "B", completed: false }, + ]; + + const result = Todos.deleteCompleted(todos); + + expect(result).toEqual(todos); + }); +});