diff --git a/Sprint-2/debug/address.js b/Sprint-2/debug/address.js index 940a6af83..55a601a23 100644 --- a/Sprint-2/debug/address.js +++ b/Sprint-2/debug/address.js @@ -1,5 +1,5 @@ // Predict and explain first... - +// it will log out the houseNumber from the address object, but it isn't working because the property name is incorrect. The correct property name is "houseNumber", not "houseNum". // 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,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 8c2125977..baa24e172 100644 --- a/Sprint-2/debug/author.js +++ b/Sprint-2/debug/author.js @@ -1,7 +1,10 @@ // Predict and explain first... +//You’ll get an error + // 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 +// The for...of loop is used to iterate over iterable objects like arrays, strings, etc. const author = { firstName: "Zadie", @@ -11,6 +14,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 6cbdd22cd..9c347638f 100644 --- a/Sprint-2/debug/recipe.js +++ b/Sprint-2/debug/recipe.js @@ -1,5 +1,6 @@ // Predict and explain first... - +//Prediction: The program will print the recipe title and number of servings, but instead of printing the ingredients, it will display [object Object]. +//recipe is the whole object, so JavaScript will convert it to: object Object // 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? @@ -11,5 +12,8 @@ const recipe = { }; console.log(`${recipe.title} serves ${recipe.serves} - ingredients: -${recipe}`); + 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..887889545 100644 --- a/Sprint-2/implement/contains.js +++ b/Sprint-2/implement/contains.js @@ -1,3 +1,8 @@ -function contains() {} +function contains(object, propertyName) { + if (object === null || typeof object !== "object" || Array.isArray(object)) { + return false; + } + return Object.hasOwn(object, propertyName); +} module.exports = contains; diff --git a/Sprint-2/implement/contains.test.js b/Sprint-2/implement/contains.test.js index 326bdb1f2..132757906 100644 --- a/Sprint-2/implement/contains.test.js +++ b/Sprint-2/implement/contains.test.js @@ -20,16 +20,27 @@ as the object doesn't contains a key of 'c' // Given an empty object // When passed to contains // Then it should return false -test.todo("contains on empty object returns false"); +test("contains on an empty object returns false", () => { + expect(contains({}, "propertyName")).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 the property exists", () => { + expect(contains({ a: 1, b: 2 }, "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 the property doesn't exist", () => { + expect(contains({ a: 1, b: 2 }, "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 input types", () => { + expect(contains([1, 2, 3], "0")).toBe(false); +}); diff --git a/Sprint-2/implement/lookup.js b/Sprint-2/implement/lookup.js index a6746e07f..da5b177d4 100644 --- a/Sprint-2/implement/lookup.js +++ b/Sprint-2/implement/lookup.js @@ -1,5 +1,11 @@ -function createLookup() { - // implementation here +function createLookup(countryCurrencyPairs) { + const lookup = {}; + + for (const [countryCode, currencyCode] of countryCurrencyPairs) { + 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 547e06c5a..ec6e05ff0 100644 --- a/Sprint-2/implement/lookup.test.js +++ b/Sprint-2/implement/lookup.test.js @@ -1,7 +1,16 @@ const createLookup = require("./lookup.js"); -test.todo("creates a country currency code lookup for multiple codes"); - +test("creates a country currency code lookup for multiple codes", () => { + const countryCurrencyPairs = [ + ["US", "USD"], + ["CA", "CAD"], + ]; + + expect(createLookup(countryCurrencyPairs)).toEqual({ + US: "USD", + CA: "CAD", + }); +}); /* Create a lookup object of key value pairs from an array of code pairs diff --git a/Sprint-2/implement/querystring.js b/Sprint-2/implement/querystring.js index 45ec4e5f3..e6531349f 100644 --- a/Sprint-2/implement/querystring.js +++ b/Sprint-2/implement/querystring.js @@ -6,10 +6,29 @@ function parseQueryString(queryString) { const keyValuePairs = queryString.split("&"); for (const pair of keyValuePairs) { - const [key, value] = pair.split("="); - queryParams[key] = value; - } + if (pair === "") { + continue; + } + + const separatorIndex = pair.indexOf("="); + + const encodedKey = + separatorIndex === -1 ? pair : pair.slice(0, separatorIndex); + const encodedValue = + separatorIndex === -1 ? "" : pair.slice(separatorIndex + 1); + + const key = decodeURIComponent(encodedKey.replaceAll("+", " ")); + const value = decodeURIComponent(encodedValue.replaceAll("+", " ")); + + if (!Object.hasOwn(queryParams, key)) { + queryParams[key] = value; + } else if (Array.isArray(queryParams[key])) { + queryParams[key].push(value); + } else { + queryParams[key] = [queryParams[key], value]; + } + } return queryParams; } diff --git a/Sprint-2/implement/tally.js b/Sprint-2/implement/tally.js index f47321812..0321fa7d8 100644 --- a/Sprint-2/implement/tally.js +++ b/Sprint-2/implement/tally.js @@ -1,3 +1,14 @@ -function tally() {} +function tally(items) { + if (!Array.isArray(items)) { + throw new TypeError("Expected an array"); + } + const counts = Object.create(null); + + for (const item of items) { + counts[item] = (counts[item] || 0) + 1; + } + + return counts; +} module.exports = tally; diff --git a/Sprint-2/implement/tally.test.js b/Sprint-2/implement/tally.test.js index 2ceffa8dd..378a8706c 100644 --- a/Sprint-2/implement/tally.test.js +++ b/Sprint-2/implement/tally.test.js @@ -23,7 +23,21 @@ const tally = require("./tally.js"); // 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({}); +}); + +test("returns the count for each unique item", () => { + expect(tally(["a", "a", "b", "c"])).toEqual({ + a: 2, + b: 1, + c: 1, + }); +}); + +test("throws an error when passed a string", () => { + expect(() => tally("a, a, b")).toThrow(TypeError); +}); // Given an array with duplicate items // When passed to tally diff --git a/Sprint-2/interpret/invert.js b/Sprint-2/interpret/invert.js index bb353fb1f..8d68ed6ff 100644 --- a/Sprint-2/interpret/invert.js +++ b/Sprint-2/interpret/invert.js @@ -10,20 +10,32 @@ function invert(obj) { const invertedObj = {}; for (const [key, value] of Object.entries(obj)) { - invertedObj.key = value; + invertedObj[value] = key; } return invertedObj; } // a) What is the current return value when invert is called with { a : 1 } +// a) Before the fix, invert({ a: 1 }) returned: +// { key: 1 } // b) What is the current return value when invert is called with { a: 1, b: 2 } +// b) Before the fix, invert({ a: 1, b: 2 }) returned: +// { key: 2 } +// The second loop replaced the first value. // c) What is the target return value when invert is called with {a : 1, b: 2} +// c) The target return value is: +// { "1": "a", "2": "b" } // c) What does Object.entries return? Why is it needed in this program? +// d) Object.entries returns an array of [key, value] pairs. +// It allows the loop to access both parts of each property. // d) Explain why the current return value is different from the target output +// e) The original code used dot notation, which created a property +// literally named "key" instead of using the value dynamically. // e) Fix the implementation of invert (and write tests to prove it's fixed!) +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..99eccda36 --- /dev/null +++ b/Sprint-2/interpret/invert.test.js @@ -0,0 +1,12 @@ +const invert = require("./invert.js"); + +test("swaps the keys and values in an object", () => { + expect(invert({ a: 1, b: 2 })).toEqual({ + 1: "a", + 2: "b", + }); +}); + +test("returns an empty object for an empty object", () => { + expect(invert({})).toEqual({}); +}); diff --git a/Sprint-2/stretch/count-words.js b/Sprint-2/stretch/count-words.js index 8e85d19d7..c45a4cca6 100644 --- a/Sprint-2/stretch/count-words.js +++ b/Sprint-2/stretch/count-words.js @@ -26,3 +26,18 @@ 3. Order the results to find out which word is the most common in the input */ +function countWords(text) { + const cleanedText = text.toLowerCase().replace(/[.,!?]/g, ""); + + const words = cleanedText.split(" ").filter((word) => word !== ""); + + const wordCounts = {}; + + for (const word of words) { + wordCounts[word] = (wordCounts[word] || 0) + 1; + } + + return wordCounts; +} + +module.exports = countWords; diff --git a/Sprint-2/stretch/mode.js b/Sprint-2/stretch/mode.js index 3f7609d79..0df943e7b 100644 --- a/Sprint-2/stretch/mode.js +++ b/Sprint-2/stretch/mode.js @@ -8,11 +8,10 @@ // 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(); +function countFrequencies(list) { + const freqs = new Map(); - for (let num of list) { + for (const num of list) { if (typeof num !== "number") { continue; } @@ -20,10 +19,14 @@ function calculateMode(list) { freqs.set(num, (freqs.get(num) || 0) + 1); } - // Find the value with the highest frequency + return freqs; +} + +function findHighestFrequency(frequencies) { let maxFreq = 0; let mode; - for (let [num, freq] of freqs) { + + for (const [num, freq] of frequencies) { if (freq > maxFreq) { mode = num; maxFreq = freq; @@ -33,4 +36,9 @@ function calculateMode(list) { return maxFreq === 0 ? NaN : mode; } +function calculateMode(list) { + const frequencies = countFrequencies(list); + return findHighestFrequency(frequencies); +} + module.exports = calculateMode; diff --git a/Sprint-2/stretch/till.js b/Sprint-2/stretch/till.js index 6a08532e7..739e1389c 100644 --- a/Sprint-2/stretch/till.js +++ b/Sprint-2/stretch/till.js @@ -8,24 +8,23 @@ function totalTill(till) { let total = 0; for (const [coin, quantity] of Object.entries(till)) { - total += coin * quantity; + const coinValue = parseInt(coin, 10); + total += coinValue * quantity; } return `£${total / 100}`; } -const till = { - "1p": 10, - "5p": 6, - "50p": 4, - "20p": 10, -}; -const totalAmount = totalTill(till); - // a) What is the target output when totalTill is called with the till object +// a) The target output is £4.4 // b) Why do we need to use Object.entries inside the for...of loop in this function? +// b) Object.entries converts the object into key-value pairs, +// allowing us to access both the coin and its quantity. // c) What does coin * quantity evaluate to inside the for...of loop? +// c) coinValue * quantity calculates the total value +// of that type of coin. // d) Write a test for this function to check it works and then fix the implementation of totalTill +module.exports = totalTill; diff --git a/Sprint-2/stretch/till.test.js b/Sprint-2/stretch/till.test.js new file mode 100644 index 000000000..ae99f8c52 --- /dev/null +++ b/Sprint-2/stretch/till.test.js @@ -0,0 +1,16 @@ +const totalTill = require("./till.js"); + +test("calculates the total amount in the till", () => { + const till = { + "1p": 10, + "5p": 6, + "50p": 4, + "20p": 10, + }; + + expect(totalTill(till)).toBe("£4.4"); +}); + +test("returns £0 for an empty till", () => { + expect(totalTill({})).toBe("£0"); +});