diff --git a/Sprint-2/debug/address.js b/Sprint-2/debug/address.js index 940a6af832..f235744711 100644 --- a/Sprint-2/debug/address.js +++ b/Sprint-2/debug/address.js @@ -1,5 +1,9 @@ // Predict and explain first... +// Prediction =======> My house number is undefined + +// Explanation ========> Because JavaScript objects store data in key-value pairs rather than zero-indexed positions like arrays, accessing address[0] looks for a non-existent key '0' and evaluates to undefined, meaning you must use dot or bracket notation with the property name instead. + // This code should log out the houseNumber from the address object // but it isn't working... // Fix anything that isn't working @@ -12,4 +16,4 @@ const address = { postcode: "XYZ 123", }; -console.log(`My house number is ${address[0]}`); +console.log(`My house number is ${address.houseNumber}`); diff --git a/Sprint-2/debug/author.js b/Sprint-2/debug/author.js index 8c2125977d..1727d69ab6 100644 --- a/Sprint-2/debug/author.js +++ b/Sprint-2/debug/author.js @@ -1,5 +1,9 @@ // Predict and explain first... +// Prediction ======> TypeError: author is not iterable at Object + +// Explanation ======> Because plain JavaScript objects are not iterable, attempting to use a for...of loop directly on the object throws an error, meaning you must use Object.values(author) to loop through its values instead. + // 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 @@ -11,6 +15,6 @@ const author = { alive: true, }; -for (const value of author) { +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 6cbdd22cdc..60099da67d 100644 --- a/Sprint-2/debug/recipe.js +++ b/Sprint-2/debug/recipe.js @@ -1,5 +1,9 @@ // Predict and explain first... +// Prediction ======> bruschetta serves 2 ingredients:[object Object] + +// Explanation ======> Because template literals automatically convert objects into the string [object Object] rather than listing their properties, logging ${recipe} fails to display the ingredients array, meaning you must iterate through recipe.ingredients using a for...of loop or .forEach() to log each item on a new line. + // This program should log out the title, how many it serves and the ingredients. // Each ingredient should be logged on a new line // How can you fix it? @@ -12,4 +16,8 @@ const recipe = { console.log(`${recipe.title} serves ${recipe.serves} ingredients: -${recipe}`); +`); + +for (const ingredient of recipe.ingredients) { + console.log(ingredient); +} diff --git a/Sprint-2/implement/contains.js b/Sprint-2/implement/contains.js index cd779308a0..2c8f4b82c5 100644 --- a/Sprint-2/implement/contains.js +++ b/Sprint-2/implement/contains.js @@ -1,3 +1,11 @@ -function contains() {} +function contains(obj, propertyName) { + // Check if obj is null, not an object type, or is an array + if (obj === null || typeof obj !== "object" || Array.isArray(obj)) { + throw new Error("contains requires an object"); + } + + // Check if the object has the specified property key + return Object.hasOwn(obj, propertyName); +} module.exports = contains; diff --git a/Sprint-2/implement/contains.test.js b/Sprint-2/implement/contains.test.js index 719272787d..a6a11c1a5d 100644 --- a/Sprint-2/implement/contains.test.js +++ b/Sprint-2/implement/contains.test.js @@ -20,21 +20,52 @@ as an array isn't an object // When passed an object and a property name // Then it should return true if the object contains the property, false otherwise -// Given an empty object -// When passed to contains -// Then it should return false -test.todo("contains on empty object returns false"); - -// Given an object with properties -// When passed to contains with an existing property name -// Then it should return true - -// Given an object with properties -// When passed to contains with a non-existent property name -// Then it should return false - -// Given a value that isn't an object - an array, a string, a number, -// null, or no argument at all -// When passed to contains -// Then it should throw Error("contains requires an object") -// (careful: typeof [] and typeof null are both "object") +describe("contains()", () => { + // Given an empty object + // When passed to contains + // Then it should return 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 an existing property name", () => { + 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 name", () => { + const obj = { a: 1, b: 2 }; + expect(contains(obj, "c")).toBe(false); + }); + + // Given a value that isn't an object - an array, a string, a number, + // null, or no argument at all + // When passed to contains + // Then it should throw Error("contains requires an object") + // (careful: typeof [] and typeof null are both "object") + test("throws an error when passed an array", () => { + expect(() => contains([1, 2, 3], "a")).toThrow("contains requires an object"); + }); + + test("throws an error when passed a string", () => { + expect(() => contains("hello", "a")).toThrow("contains requires an object"); + }); + + test("throws an error when passed a number", () => { + expect(() => contains(42, "a")).toThrow("contains requires an object"); + }); + + test("throws an error when passed null", () => { + expect(() => contains(null, "a")).toThrow("contains requires an object"); + }); + + test("throws an error when passed no arguments", () => { + expect(() => contains()).toThrow("contains requires an object"); + }); +}); \ No newline at end of file diff --git a/Sprint-2/implement/lookup.js b/Sprint-2/implement/lookup.js index a6746e07f5..aea7831874 100644 --- a/Sprint-2/implement/lookup.js +++ b/Sprint-2/implement/lookup.js @@ -1,5 +1,15 @@ -function createLookup() { - // implementation here -} + + + function createLookup(pairs) { + // implementation here + const lookup = {}; + + for (const [countryCode, currencyCode] of pairs) { + lookup[countryCode] = currencyCode; + } + + return lookup; + } + module.exports = createLookup; diff --git a/Sprint-2/implement/lookup.test.js b/Sprint-2/implement/lookup.test.js index 547e06c5a7..f7bc819ab8 100644 --- a/Sprint-2/implement/lookup.test.js +++ b/Sprint-2/implement/lookup.test.js @@ -1,7 +1,5 @@ const createLookup = require("./lookup.js"); -test.todo("creates a country currency code lookup for multiple codes"); - /* Create a lookup object of key value pairs from an array of code pairs @@ -33,3 +31,33 @@ It should return: 'CA': 'CAD' } */ + +describe("createLookup()", () => { + test("creates a country currency code lookup for multiple codes", () => { + const pairs = [ + ["US", "USD"], + ["CA", "CAD"], + ["GB", "GBP"], + ]; + + const expected = { + US: "USD", + CA: "CAD", + GB: "GBP", + }; + + expect(createLookup(pairs)).toEqual(expected); + }); + + test("returns an empty object when passed an empty array", () => { + expect(createLookup([])).toEqual({}); + }); + + test("creates a lookup object for a single pair", () => { + const pairs = [["FR", "EUR"]]; + const expected = { FR: "EUR" }; + + expect(createLookup(pairs)).toEqual(expected); + }); +}); + diff --git a/Sprint-2/implement/querystring.js b/Sprint-2/implement/querystring.js index 45ec4e5f37..bf2e8745d8 100644 --- a/Sprint-2/implement/querystring.js +++ b/Sprint-2/implement/querystring.js @@ -1,16 +1,50 @@ function parseQueryString(queryString) { const queryParams = {}; - if (queryString.length === 0) { + if (!queryString) { return queryParams; } + const keyValuePairs = queryString.split("&"); for (const pair of keyValuePairs) { - const [key, value] = pair.split("="); - queryParams[key] = value; + if (!pair) continue; // Ignore empty pairs + + const index = pair.indexOf("="); + let rawKey, rawValue; + + if (index === -1) { + rawKey = pair; + rawValue = ""; + } else { + rawKey = pair.slice(0, index); + rawValue = pair.slice(index + 1); + } + + // Helper to decode URI components and replace '+' with spaces + const decode = (str) => { + try { + return decodeURIComponent(str.replace(/\+/g, " ")); + } catch (e) { + return str.replace(/\+/g, " "); + } + }; + + const key = decode(rawKey); + const value = decode(rawValue); + + // Handle duplicate keys by storing multiple values in an array + if (Object.hasOwn(queryParams, key)) { + if (Array.isArray(queryParams[key])) { + queryParams[key].push(value); + } else { + queryParams[key] = [queryParams[key], value]; + } + } else { + queryParams[key] = value; + } } return queryParams; } -module.exports = parseQueryString; +module.exports = parseQueryString; \ No newline at end of file diff --git a/Sprint-2/implement/tally.js b/Sprint-2/implement/tally.js index f47321812e..5aecc35e93 100644 --- a/Sprint-2/implement/tally.js +++ b/Sprint-2/implement/tally.js @@ -1,3 +1,24 @@ -function tally() {} +// function tally() {} + +// module.exports = tally; + +function tally(arr) { + // Check if arr is not an array (handling strings, numbers, null, undefined, or objects) + if (!Array.isArray(arr)) { + throw new Error("tally requires an array"); + } + + const result = {}; + + for (const item of arr) { + if (Object.prototype.hasOwnProperty.call(result, item)) { + result[item] += 1; + } else { + result[item] = 1; + } + } + + return result; +} module.exports = tally; diff --git a/Sprint-2/implement/tally.test.js b/Sprint-2/implement/tally.test.js index ca763c2965..ce4af1dd21 100644 --- a/Sprint-2/implement/tally.test.js +++ b/Sprint-2/implement/tally.test.js @@ -16,19 +16,41 @@ const tally = require("./tally.js"); // Acceptance criteria: -// Given a function called tally -// When passed an array of items -// Then it should return an object containing the count for each unique item - -// Given an empty array -// When passed to tally -// Then it should return an empty object -test.todo("tally on an empty array returns an empty object"); - -// Given an array with duplicate items -// When passed to tally -// Then it should return counts for each unique item - -// Given an invalid input like a string, a number, or no argument at all -// When passed to tally -// Then it should throw Error("tally requires an array") +describe("tally()", () => { + // Given an empty array + // When passed to tally + // Then it should return an empty object + + test("tally on an empty array returns an empty object", () => { + expect(tally([])).toEqual({}); + }); + + // Given an array with duplicate items + // When passed to tally + // Then it should return counts for each unique item + + test("returns counts for each unique item when passed an array with duplicates", () => { + expect(tally(["a"])).toEqual({ a: 1 }); + expect(tally(["a", "a", "a"])).toEqual({ a: 3 }); + expect(tally(["a", "a", "b", "c"])).toEqual({ a: 2, b: 1, c: 1 }); + }); + + // Given an invalid input like a string, a number, or no argument at all + // When passed to tally + // Then it should throw Error("tally requires an array") + test("throws an error when passed a string", () => { + expect(() => tally("hello")).toThrow("tally requires an array"); + }); + + test("throws an error when passed a number", () => { + expect(() => tally(42)).toThrow("tally requires an array"); + }); + + test("throws an error when passed null", () => { + expect(() => tally(null)).toThrow("tally requires an array"); + }); + + test("throws an error when passed no arguments", () => { + expect(() => tally()).toThrow("tally requires an array"); + }); +}); diff --git a/Sprint-2/interpret/invert.js b/Sprint-2/interpret/invert.js index bb353fb1fd..c3b7c7d9e9 100644 --- a/Sprint-2/interpret/invert.js +++ b/Sprint-2/interpret/invert.js @@ -10,20 +10,28 @@ function invert(obj) { const invertedObj = {}; for (const [key, value] of Object.entries(obj)) { - invertedObj.key = value; + invertedObj[value] = key; } return invertedObj; } +module.exports = invert; + // a) What is the current return value when invert is called with { a : 1 } +// Answer: Return value when called with { a : 1 } { key: 1 } // b) What is the current return value when invert is called with { a: 1, b: 2 } +// Answer: Return value when called with { a: 1, b: 2 } { key: 2 } (because the loop runs twice, overwriting invertedObj.key each time) // c) What is the target return value when invert is called with {a : 1, b: 2} +// Answer: Target return value when called with { a : 1, b: 2 } { "1": "a", "2": "b" } // c) What does Object.entries return? Why is it needed in this program? +// Answer: Object.entries() takes an object and turns it into a list of [key, value] pairs so that a loop can read them.Because plain JavaScript objects can't be looped through directly by themselves, Object.entries() acts like a translator—it converts your object into a list (like [['a', 1], ['b', 2]]) so you can easily grab both the keys and values at the same time. // d) Explain why the current return value is different from the target output +// Answer: It writes the literal word "key": Writing invertedObj.key = value tells JavaScript to literally create a property named "key" over and over again, instead of using bracket notation (invertedObj[value]) to look up and use the actual variable value. +// It doesn't actually swap them: The code assigns the original value to key, whereas an inversion needs to flip them so the original value becomes the new key pointing back to the original key (invertedObj[value] = key). // e) Fix the implementation of invert (and write tests to prove it's fixed!) diff --git a/Sprint-2/interpret/invert.test.js b/Sprint-2/interpret/invert.test.js new file mode 100644 index 0000000000..ff0adbb3be --- /dev/null +++ b/Sprint-2/interpret/invert.test.js @@ -0,0 +1,12 @@ +const invert = require("./invert.js"); + +describe("invert()", () => { + test("swaps the keys and values in an object", () => { + expect(invert({ x: 10, y: 20 })).toEqual({ "10": "x", "20": "y" }); + expect(invert({ a: 1, b: 2 })).toEqual({ "1": "a", "2": "b" }); + }); + + test("returns an empty object when passed an empty object", () => { + expect(invert({})).toEqual({}); + }); +}); \ No newline at end of file