diff --git a/Sprint-2/debug/address.js b/Sprint-2/debug/address.js index 940a6af83..d621040b2 100644 --- a/Sprint-2/debug/address.js +++ b/Sprint-2/debug/address.js @@ -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}`); +// console.log(`My house number is ${address[0]}`); + +// The original syntax works for array and not for object. +// it will show undefine message +// Instead use the correct . operator to access the object field values diff --git a/Sprint-2/debug/author.js b/Sprint-2/debug/author.js index 8c2125977..50447e4ff 100644 --- a/Sprint-2/debug/author.js +++ b/Sprint-2/debug/author.js @@ -11,6 +11,14 @@ const author = { alive: true, }; -for (const value of author) { - console.log(value); +// for (const value of author) { +// console.log(value); +// } + +for (const key in author) { + console.log(author[key]); } + +// the iteration method does not work for the object. +// TypeError TypeError: author is not iterable will be shown +// Change the correct method with the object diff --git a/Sprint-2/debug/recipe.js b/Sprint-2/debug/recipe.js index 6cbdd22cd..e279a0145 100644 --- a/Sprint-2/debug/recipe.js +++ b/Sprint-2/debug/recipe.js @@ -10,6 +10,14 @@ const recipe = { ingredients: ["olive oil", "tomatoes", "salt", "pepper"], }; -console.log(`${recipe.title} serves ${recipe.serves} - ingredients: -${recipe}`); +//console.log(`${recipe.title} serves ${recipe.serves} +// ingredients: +//${recipe}`); + +for (const ingredient of recipe.ingredients) { + console.log(ingredient); +} + + +// [object Object] will be shown because JavaScript converts an object to a string, it becomes "[object object]. +// Use the syntax to access the ingredients directly diff --git a/Sprint-2/implement/contains.js b/Sprint-2/implement/contains.js index cd779308a..4f8354667 100644 --- a/Sprint-2/implement/contains.js +++ b/Sprint-2/implement/contains.js @@ -1,3 +1,13 @@ -function contains() {} +function 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.prototype.hasOwnProperty.call(obj, prop); + +} module.exports = contains; diff --git a/Sprint-2/implement/contains.test.js b/Sprint-2/implement/contains.test.js index 326bdb1f2..2daa43068 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); + }); diff --git a/Sprint-2/implement/lookup.js b/Sprint-2/implement/lookup.js index a6746e07f..63ed72807 100644 --- a/Sprint-2/implement/lookup.js +++ b/Sprint-2/implement/lookup.js @@ -1,4 +1,8 @@ function createLookup() { + + return Object.fromEntries(countryCurrencyPairs); + + // implementation here } diff --git a/Sprint-2/implement/lookup.test.js b/Sprint-2/implement/lookup.test.js index 547e06c5a..e2f8f1801 100644 --- a/Sprint-2/implement/lookup.test.js +++ b/Sprint-2/implement/lookup.test.js @@ -1,35 +1,20 @@ 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 - -Acceptance Criteria: - -Given - - An array of arrays representing country code and currency code pairs - e.g. [['US', 'USD'], ['CA', 'CAD']] - -When - - createLookup function is called with the country-currency array as an argument - -Then - - It should return an object where: - - The keys are the country codes - - The values are the corresponding currency codes - -Example -Given: [['US', 'USD'], ['CA', 'CAD']] - -When -createLookup(countryCurrencyPairs) is called - -Then -It should return: - { - 'US': 'USD', - 'CA': 'CAD' - } -*/ +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); +}); diff --git a/Sprint-2/implement/querystring.js b/Sprint-2/implement/querystring.js index 45ec4e5f3..7bf291348 100644 --- a/Sprint-2/implement/querystring.js +++ b/Sprint-2/implement/querystring.js @@ -1,13 +1,50 @@ 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; diff --git a/Sprint-2/implement/querystring.test.js b/Sprint-2/implement/querystring.test.js index 328b8df61..962ecf8a7 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", () => { diff --git a/Sprint-2/implement/tally.js b/Sprint-2/implement/tally.js index f47321812..16c800576 100644 --- a/Sprint-2/implement/tally.js +++ b/Sprint-2/implement/tally.js @@ -1,3 +1,12 @@ -function tally() {} +function tally(items) { + if (!Array.isArray(items)) { + throw new TypeError("Expected an array as input"); + } + + return items.reduce((acc, item) => { + acc[item] = (acc[item] || 0) + 1; + return acc; + }, {}); +} module.exports = tally; diff --git a/Sprint-2/implement/tally.test.js b/Sprint-2/implement/tally.test.js index 2ceffa8dd..ced8a644e 100644 --- a/Sprint-2/implement/tally.test.js +++ b/Sprint-2/implement/tally.test.js @@ -19,16 +19,30 @@ 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(TypeError); + expect(() => tally("string")).toThrow("Expected an array as input"); + }); diff --git a/Sprint-2/interpret/invert.js b/Sprint-2/interpret/invert.js index bb353fb1f..1780b9993 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; diff --git a/Sprint-2/stretch/count-words.js b/Sprint-2/stretch/count-words.js index 8e85d19d7..811033859 100644 --- a/Sprint-2/stretch/count-words.js +++ b/Sprint-2/stretch/count-words.js @@ -26,3 +26,27 @@ 3. Order the results to find out which word is the most common in the input */ + +function countWords(str) { + if (typeof str !== "string") { + throw new TypeError("Expected a string as input"); + } + + // Handle empty or whitespace-only strings + if (str.trim() === "") return {}; + + const words = str.split(" "); + const counts = {}; + + for (const word of words) { + if (counts[word]) { + counts[word] += 1; + } else { + counts[word] = 1; + } + } + + return counts; +} + +module.exports = countWords; diff --git a/Sprint-2/stretch/mode.js b/Sprint-2/stretch/mode.js index 3f7609d79..b7bc5138b 100644 --- a/Sprint-2/stretch/mode.js +++ b/Sprint-2/stretch/mode.js @@ -8,6 +8,7 @@ // refactor calculateMode by splitting up the code // into smaller functions using the stages above +/* function calculateMode(list) { // track frequency of each value let freqs = new Map(); @@ -34,3 +35,43 @@ function calculateMode(list) { } module.exports = calculateMode; +*/ + +function getFrequencies(list) { + const freqs = new Map(); + + for (const num of list) { + if (typeof num !== "number") { + continue; + } + freqs.set(num, (freqs.get(num) || 0) + 1); + } + + return freqs; +} + + +function getHighestFrequencyKey(freqs) { + let maxFreq = 0; + let mode; + + for (const [num, freq] of freqs) { + if (freq > maxFreq) { + mode = num; + maxFreq = freq; + } + } + + return maxFreq === 0 ? NaN : mode; +} + +function calculateMode(list) { + const freqs = getFrequencies(list); + return getHighestFrequencyKey(freqs); +} + +module.exports = { + calculateMode, + getFrequencies, + getHighestFrequencyKey, +}; diff --git a/Sprint-2/stretch/till.js b/Sprint-2/stretch/till.js index 6a08532e7..d52e37433 100644 --- a/Sprint-2/stretch/till.js +++ b/Sprint-2/stretch/till.js @@ -23,9 +23,41 @@ const till = { const totalAmount = totalTill(till); // a) What is the target output when totalTill is called with the till object - +"£4.40" // b) Why do we need to use Object.entries inside the for...of loop in this function? - +We need it because plain objects are not directly iterable using a for...of loop in JavaScript. Using Object.entries allows us to loop through the entries // c) What does coin * quantity evaluate to inside the for...of loop? - +coin * quantity evaluates to NaN (Not-a-Number). // d) Write a test for this function to check it works and then fix the implementation of totalTill + function totalTill(till) { + let totalPence = 0; + + for (const [coin, quantity] of Object.entries(till)) { + // Parse the numeric pence value from strings like "50p" -> 50 + const penceValue = parseInt(coin, 10); + + if (!isNaN(penceValue)) { + totalPence += penceValue * quantity; + } + } + + // Convert pence to pounds and format to 2 decimal places + const pounds = (totalPence / 100).toFixed(2); + return `£${pounds}`; +} + +module.exports = totalTill; + +const totalTill = require("./totalTill.js"); + +describe("totalTill", () => { + test("calculates the correct total for a given till object", () => { + const till = { + "1p": 10, + "5p": 6, + "50p": 4, + "20p": 10, + }; + expect(totalTill(till)).toBe("£4.40"); + }); +});