diff --git a/Sprint-2/debug/address.js b/Sprint-2/debug/address.js index 940a6af83..ae4fe0565 100644 --- a/Sprint-2/debug/address.js +++ b/Sprint-2/debug/address.js @@ -1,5 +1,5 @@ // Predict and explain first... - +//'My house number is 42' // This code should log out the houseNumber from the address object // but it isn't working... // Fix anything that isn't working @@ -12,4 +12,9 @@ const address = { postcode: "XYZ 123", }; -console.log(`My house number is ${address[0]}`); +console.log(`My house number is ${address.houseNumber}`); + +// address[0] uses array-style index access. Since address is an object, we need to access the property using its property name. +// It returns undefined because the object does not have a property called 0. +// We can use dot notation (.) to access the houseNumber property of the object. +//The original syntax, address[0], uses index access, which is commonly used with arrays. Since address is an object, we need to access the property using its name. address[0] returns undefined because the object does not have a property called 0. We can use dot notation, address.houseNumber, to access the houseNumber property. \ No newline at end of file diff --git a/Sprint-2/debug/author.js b/Sprint-2/debug/author.js index 8c2125977..ff1335eee 100644 --- a/Sprint-2/debug/author.js +++ b/Sprint-2/debug/author.js @@ -11,6 +11,11 @@ const author = { alive: true, }; -for (const value of author) { - console.log(value); +for (const key in author) { + console.log(author[key]); } + +// for...of does not work with a plain object because the object is not iterable. +// It throws: TypeError: author is not iterable. +// for...in iterates over the object's property keys. +// We can use each key to access the corresponding property value. \ No newline at end of file diff --git a/Sprint-2/debug/recipe.js b/Sprint-2/debug/recipe.js index 6cbdd22cd..833b96da4 100644 --- a/Sprint-2/debug/recipe.js +++ b/Sprint-2/debug/recipe.js @@ -10,6 +10,12 @@ const recipe = { ingredients: ["olive oil", "tomatoes", "salt", "pepper"], }; -console.log(`${recipe.title} serves ${recipe.serves} - ingredients: -${recipe}`); +for (const ingredient of recipe.ingredients) { + console.log(ingredient); +} + + +/**[object Object] is shown because ${recipe} converts the +recipe object to a string using JavaScript's default object string representation. +We need to access recipe.ingredients directly and +iterate over the array using for...of.**/ \ No newline at end of file diff --git a/Sprint-2/implement/contains.js b/Sprint-2/implement/contains.js index cd779308a..74ab95353 100644 --- a/Sprint-2/implement/contains.js +++ b/Sprint-2/implement/contains.js @@ -1,3 +1,13 @@ -function contains() {} +function contains() { -module.exports = contains; + // Return false if obj is null, undefined, an array, or not a non-null object + if (typeof obj !== "object" || obj === null || Array.isArray(obj)) { + return false; + } + + // Check if the property exists directly on the object + return Object.hasOwn(obj, prop); + +} + +module.exports = contains; \ No newline at end of file diff --git a/Sprint-2/implement/contains.test.js b/Sprint-2/implement/contains.test.js index 326bdb1f2..917f6184a 100644 --- a/Sprint-2/implement/contains.test.js +++ b/Sprint-2/implement/contains.test.js @@ -17,19 +17,33 @@ as the object doesn't contains a key of 'c' // 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 invalid parameters like an array -// When passed to contains -// Then it should return false or throw an error + // 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 passed an existing property name", () => { + const inputObj = { a: 1, b: 2 }; + expect(contains(inputObj, "a")).toBe(true); + expect(contains(inputObj, "b")).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 passed a non-existent property name", () => { + const inputObj = { a: 1, b: 2 }; + expect(contains(inputObj, "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 when passed invalid parameters like arrays or primitives", () => { + expect(contains([1, 2, 3], "0")).toBe(false); + }); \ No newline at end of file diff --git a/Sprint-2/implement/lookup.js b/Sprint-2/implement/lookup.js index a6746e07f..4e05ac962 100644 --- a/Sprint-2/implement/lookup.js +++ b/Sprint-2/implement/lookup.js @@ -1,5 +1,9 @@ -function createLookup() { +function createLookup(countryCurrencyPairs) { + + return Object.fromEntries(countryCurrencyPairs); + + // implementation here } -module.exports = createLookup; +module.exports = createLookup; \ No newline at end of file diff --git a/Sprint-2/implement/lookup.test.js b/Sprint-2/implement/lookup.test.js index 547e06c5a..48016c6f5 100644 --- a/Sprint-2/implement/lookup.test.js +++ b/Sprint-2/implement/lookup.test.js @@ -1,6 +1,3 @@ -const createLookup = require("./lookup.js"); - -test.todo("creates a country currency code lookup for multiple codes"); /* @@ -33,3 +30,23 @@ It should return: 'CA': 'CAD' } */ +const createLookup = require("./lookup.js"); + +test("creates a country currency code lookup for multiple codes", () => { + // Given + const input = [ + ["US", "USD"], + ["CA", "CAD"], + ]; + + const expectedOutput = { + US: "USD", + CA: "CAD", + }; + + // When + const result = createLookup(input); + + // Then + expect(result).toEqual(expectedOutput); +}); \ No newline at end of file diff --git a/Sprint-2/implement/querystring.js b/Sprint-2/implement/querystring.js index 45ec4e5f3..447773a8b 100644 --- a/Sprint-2/implement/querystring.js +++ b/Sprint-2/implement/querystring.js @@ -1,16 +1,53 @@ function parseQueryString(queryString) { const queryParams = {}; - if (queryString.length === 0) { + + if (!queryString || queryString.length === 0) { return queryParams; } + + // Helper to decode '+' as spaces and percent-encoded characters + function decodeParam(str) { + return decodeURIComponent(str.replace(/\+/g, " ")); + } + + // Split by '&' to get raw key-value pairs const keyValuePairs = queryString.split("&"); for (const pair of keyValuePairs) { - const [key, value] = pair.split("="); - queryParams[key] = value; + // Ignore empty pairs caused by trailing or duplicate '&' (e.g. "a=1&&b=2&") + if (pair.length === 0) { + continue; + } + + let rawKey, rawValue; + const equalIndex = pair.indexOf("="); + + if (equalIndex === -1) { + // Key with no '=' (e.g., "key") -> value is empty string + rawKey = pair; + rawValue = ""; + } else { + // Split on the FIRST '=' only (handles values containing '=', e.g. "a=b-2") + rawKey = pair.slice(0, equalIndex); + rawValue = pair.slice(equalIndex + 1); + } + + const key = decodeParam(rawKey); + const value = decodeParam(rawValue); + + // Stretch Goal: Handle duplicate keys by converting to an array + if (Object.prototype.hasOwnProperty.call(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/querystring.test.js b/Sprint-2/implement/querystring.test.js index 328b8df61..256e5c9c3 100644 --- a/Sprint-2/implement/querystring.test.js +++ b/Sprint-2/implement/querystring.test.js @@ -38,6 +38,12 @@ test("should replace '+' by ' '", () => { }); // Stretch exercise: Handling query strings that contain identical keys +test("should handle multiple duplicate keys alongside single keys", () => { + expect(parseQueryString("tag=js&tag=node&author=CYF")).toEqual({ + tag: ["js", "node"], + author: "CYF", + }); +}); // Delete this test if you are not working on this optional case test("should store values of a key in an array when the key has 2 or more values", () => { @@ -45,4 +51,4 @@ test("should store values of a key in an array when the key has 2 or more values key: ["value1", "value2", "value3"], foo: "bar", }); -}); +}); \ No newline at end of file diff --git a/Sprint-2/implement/tally.js b/Sprint-2/implement/tally.js index f47321812..79a615cae 100644 --- a/Sprint-2/implement/tally.js +++ b/Sprint-2/implement/tally.js @@ -1,3 +1,16 @@ -function tally() {} +function tally(items) { + if (!Array.isArray(items)) { + throw new TypeError("Expected an array as input"); + } -module.exports = tally; + return items.reduce((acc, item) => { + if (Object.hasOwn(acc, item)) { + acc[item] += 1; + } else { + acc[item] = 1; + } + return acc; + }, {}); +} + +module.exports = tally; \ No newline at end of file diff --git a/Sprint-2/implement/tally.test.js b/Sprint-2/implement/tally.test.js index 2ceffa8dd..a7f5f179f 100644 --- a/Sprint-2/implement/tally.test.js +++ b/Sprint-2/implement/tally.test.js @@ -19,16 +19,29 @@ const tally = require("./tally.js"); // Given a function called tally // When passed an array of items // Then it should return an object containing the count for each unique item +test("returns counts for each unique item", () => { + expect(tally(["a"])).toEqual({ a: 1 }); + expect(tally(["a", "b", "c"])).toEqual({ a: 1, b: 1, c: 1 }); + }); // 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"); +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", () => { + 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 // When passed to tally // Then it should throw an error +test("throws an error when passed an invalid input like a string", () => { + expect(() => tally("string")).toThrow("Expected an array as input"); + }); \ No newline at end of file diff --git a/Sprint-2/interpret/invert.js b/Sprint-2/interpret/invert.js index bb353fb1f..a1a6deb9c 100644 --- a/Sprint-2/interpret/invert.js +++ b/Sprint-2/interpret/invert.js @@ -17,13 +17,29 @@ function invert(obj) { } // a) What is the current return value when invert is called with { a : 1 } - +{ key: 1 } // b) What is the current return value when invert is called with { a: 1, b: 2 } - +{ key: 2 } // c) What is the target return value when invert is called with {a : 1, b: 2} - +{ "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 as two-element arrays. +Object.entries({ a: 1, b: 2 }) returns [["a", 1], ["b", 2]]. // d) Explain why the current return value is different from the target output - +The line invertedObj.key = value; contains bugs: // e) Fix the implementation of invert (and write tests to prove it's fixed!) +function invert(obj) { + if (typeof obj !== "object" || obj === null || Array.isArray(obj)) { + throw new TypeError("Expected a plain object"); + } + + const invertedObj = {}; + + for (const [key, value] of Object.entries(obj)) { + invertedObj[value] = key; + } + + return invertedObj; +} + +module.exports = invert; \ No newline at end of file