diff --git a/Sprint-2/debug/address.js b/Sprint-2/debug/address.js index 940a6af83..be549d504 100644 --- a/Sprint-2/debug/address.js +++ b/Sprint-2/debug/address.js @@ -1,4 +1,6 @@ // Predict and explain first... +// prediction before running code: This leads to an error as this isn't an array where values accessed via index/position. values should be accessed via keys/properties in objects. +//observations after running code: logged out "undefined" for ${address[0]}` as this expression can't be matched with any property inside the object // This code should log out the houseNumber from the address object // but it isn't working... @@ -12,4 +14,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..346552b0d 100644 --- a/Sprint-2/debug/author.js +++ b/Sprint-2/debug/author.js @@ -1,4 +1,6 @@ // Predict and explain first... +// prediction before running code: because accessing values of objects should've been done via dot notation or the square brackets method. +//observations after running code: the "for.. of" method only works on iterable objects excluding "plain objects". "For...in" method could be used 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 +13,7 @@ const author = { alive: true, }; -for (const value of author) { - console.log(value); +for (const value in author) { + console.log(author[value]); } + diff --git a/Sprint-2/debug/recipe.js b/Sprint-2/debug/recipe.js index 6cbdd22cd..0638e9010 100644 --- a/Sprint-2/debug/recipe.js +++ b/Sprint-2/debug/recipe.js @@ -1,4 +1,6 @@ // Predict and explain first... +// prediction before running code: this template literal expression: "${recipe}" won't give the expected results for the "ingredients" part. +// observations after running code: ${recipe}` evaluates to [object Object]. This is because template literal ALONE converts an object into a string with unreadable properties. // This program should log out the title, how many it serves and the ingredients. // Each ingredient should be logged on a new line @@ -10,6 +12,4 @@ 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:\n${recipe.ingredients.join("\n")}`); diff --git a/Sprint-2/implement/contains.js b/Sprint-2/implement/contains.js index cd779308a..2a710bf5c 100644 --- a/Sprint-2/implement/contains.js +++ b/Sprint-2/implement/contains.js @@ -1,3 +1,11 @@ -function contains() {} +function contains(object, property) { + if (typeof object !== "object" || object == null || Array.isArray(object)) { + return false; + } + + return object.hasOwnProperty(property); + } + + module.exports = contains; diff --git a/Sprint-2/implement/contains.test.js b/Sprint-2/implement/contains.test.js index 326bdb1f2..1bc1eda87 100644 --- a/Sprint-2/implement/contains.test.js +++ b/Sprint-2/implement/contains.test.js @@ -20,16 +20,62 @@ 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 empty object returns false", () => { + + const currentOutput = contains({}, "2"); + const targetOutput = false; + expect(currentOutput).toEqual(targetOutput); +}); // Given an object with properties // When passed to contains with an existing property name // Then it should return true +const user = { + id: 101, + name: "Amina Yusuf", + email: "amina@example.com", + isVerified: true, +}; +test("an object contains an existing property name returns true", () => { + const currentOutput = contains(user, "name"); + const targetOutput = true; + expect(currentOutput).toEqual(targetOutput); +}); // Given an object with properties // When passed to contains with a non-existent property name // Then it should return false +const book = { + title: "Harry Potter and the Sorcerer's Stone", + author: "J.K. Rowling", + publishedYear: 1997, + genres: "Fantasy", + pages: 309 +}; + +test("an object doesn't contain a property name returns false", () => { + const currentOutput = contains(book, "series"); + const targetOutput = false; + expect(currentOutput).toEqual(targetOutput); +}); + // Given invalid parameters like an array // When passed to contains // Then it should return false or throw an error + +const programmingLanguages = ["JavaScript", "Python", "Java", "C++", "Go", "Rust", "Ruby"]; +const languages = null; +const name = "Hassan"; + +test("Returns false when invalid parameters are passed", () => { + const currentOutput = contains(programmingLanguages, "3"); + const targetOutput = false; + expect(currentOutput).toEqual(targetOutput); + const currentOutput1 = contains(languages, "null"); + const targetOutput1 = false; + expect(currentOutput1).toEqual(targetOutput1); + const currentOutput2 = contains(name, "Hassan"); + const targetOutput2 = false; + expect(currentOutput2).toEqual(targetOutput2); +}); diff --git a/Sprint-2/implement/lookup.js b/Sprint-2/implement/lookup.js index a6746e07f..d24b0eff0 100644 --- a/Sprint-2/implement/lookup.js +++ b/Sprint-2/implement/lookup.js @@ -1,5 +1,6 @@ -function createLookup() { - // implementation here +function createLookup(array) { + return Object.fromEntries(array); + } module.exports = createLookup; diff --git a/Sprint-2/implement/lookup.test.js b/Sprint-2/implement/lookup.test.js index 547e06c5a..28e4bab3d 100644 --- a/Sprint-2/implement/lookup.test.js +++ b/Sprint-2/implement/lookup.test.js @@ -1,6 +1,19 @@ const createLookup = require("./lookup.js"); -test.todo("creates a country currency code lookup for multiple codes"); +const countryCurrencyPairs = [["US", "USD"], ["GB", "GBP"], ["JP", "JPY"], ["NG", "NGN"], ["IN", "INR"], ["CA", "CAD"]]; + +test("creates a country currency code lookup for multiple codes", () => { + const currentOutput = createLookup(countryCurrencyPairs); + const targetOutput = { + US: "USD", + GB: "GBP", + JP: "JPY", + NG: "NGN", + IN: "INR", + CA: "CAD" +}; +expect(currentOutput).toEqual(targetOutput); +}); /* diff --git a/Sprint-2/implement/querystring.js b/Sprint-2/implement/querystring.js index 45ec4e5f3..3d8d2754b 100644 --- a/Sprint-2/implement/querystring.js +++ b/Sprint-2/implement/querystring.js @@ -3,14 +3,24 @@ function parseQueryString(queryString) { if (queryString.length === 0) { return queryParams; } + const keyValuePairs = queryString.split("&"); for (const pair of keyValuePairs) { - const [key, value] = pair.split("="); - queryParams[key] = value; - } + const separatorIndex = pair.indexOf("="); + if (separatorIndex === -1) { + queryParams[pair] = ""; + } else { + const key = decodeURIComponent(pair.slice(0, separatorIndex)); + const value = decodeURIComponent(pair.slice(separatorIndex + 1)); + queryParams[key] = value; + } + } return queryParams; } module.exports = parseQueryString; + + +console.log(parseQueryString("equation=x=y+1")); \ No newline at end of file diff --git a/Sprint-2/implement/querystring.test.js b/Sprint-2/implement/querystring.test.js index 3e218b789..ed26cf03a 100644 --- a/Sprint-2/implement/querystring.test.js +++ b/Sprint-2/implement/querystring.test.js @@ -5,8 +5,53 @@ const parseQueryString = require("./querystring.js") +test("parses querystring values containing multiple '=' signs", () => { + expect(parseQueryString("name=JohnDoe&age=30&country=Canada&sort=recent&showDetails=true")).toEqual({ + name: "JohnDoe", + age: "30", + country: "Canada", + sort: "recent", + showDetails: "true" +}); +}); + + + +test("parses an empty querystring & returns an empty object", () => { + expect(parseQueryString("")).toEqual({}); +}); + + + + test("parses querystring values containing =", () => { expect(parseQueryString("equation=x=y+1")).toEqual({ - "equation": "x=y+1", + equation: "x=y+1", }); }); + + + + +test("parses querystring values without '=' & returns keys only", () => { + expect(parseQueryString("fullName")).toEqual({fullName: "" }); +}); + + + + +test("parses querystring with duplicate/repeated keys & returns the last key-value pair", () => { + expect(parseQueryString("haircut=buzzCut&haircut=mullet&haircut=lowFade&shaver=braun&shaver=philips&shaver=wahl")).toEqual({ + haircut: "lowFade", + shaver: "wahl", + }); +}); + + +test("parses an encoded querystring & returns decoded key-value pairs", () => { + expect(parseQueryString("name=John%20Doe&email=john.doe%40example.com&message=Hello%2C%20how%20are%20you%3F")).toEqual({ + name: "John Doe", + email: "john.doe@example.com", + message: "Hello, how are you?" + }) +}) \ No newline at end of file diff --git a/Sprint-2/implement/tally.js b/Sprint-2/implement/tally.js index f47321812..ac72490c9 100644 --- a/Sprint-2/implement/tally.js +++ b/Sprint-2/implement/tally.js @@ -1,3 +1,11 @@ -function tally() {} +function tally(list) { + if (!Array.isArray(list)) { + throw new Error("Invalid input!"); + } + return list.reduce((rep, element) => { + rep[element] = (rep[element] || 0) + 1; + return rep; + }, {}); +} module.exports = tally; diff --git a/Sprint-2/implement/tally.test.js b/Sprint-2/implement/tally.test.js index 2ceffa8dd..2f2fb90e9 100644 --- a/Sprint-2/implement/tally.test.js +++ b/Sprint-2/implement/tally.test.js @@ -23,12 +23,36 @@ 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"); + +const emptyArray = []; + +test("tally on an empty array returns an empty object", () => { + const currentOutput = tally(emptyArray); + const targetOutput = {}; + expect(currentOutput).toEqual(targetOutput); +}); // Given an array with duplicate items // When passed to tally // Then it should return counts for each unique item +const animals = ['cat', 'dog', 'cat', 'bird', 'dog', 'dog', 'rabbit', 'cat']; + +test("tally on an array returns an object with the frequency of each item as properties", () => { + const currentOutput = tally(animals); + const targetOutput = {cat: 3, dog: 3, bird: 1, rabbit: 1}; + expect(currentOutput).toEqual(targetOutput); +}); + // Given an invalid input like a string // When passed to tally // Then it should throw an error + +test("tally throws an error when given invalid input", () => { + const name = "Hassan"; + const age = null; + const subjectsHobbies = {Math: "puzzles", Science: "experiments", Art: "drawing"}; + expect(() => tally(name)).toThrow("Invalid input!"); + expect(() => tally(age)).toThrow("Invalid input!"); + expect(() => tally(subjectsHobbies)).toThrow("Invalid input!"); +}); \ No newline at end of file diff --git a/Sprint-2/interpret/invert.js b/Sprint-2/interpret/invert.js index bb353fb1f..6e5f71e0f 100644 --- a/Sprint-2/interpret/invert.js +++ b/Sprint-2/interpret/invert.js @@ -17,13 +17,55 @@ 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 } +// b) What is the current return value when invert is called with +//{ 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? +// it returns an array of key-value pairs from an object. +//it's needed in order to loop through each key-value pairs of an object. // d) Explain why the current return value is different from the target output +// because line 13 is not written accordingly. The current arrangement always starts with keys and then values. +// Most importantly, there's a bug. Currently, it returns "key" as if it's a key/property name. Refer to (a & b) + + // 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; +} + + +const sports = { + soccer: "ball", + tennis: "racket", + basketball: "hoopBall", + baseball: "bat", + swimming: "goggles", +}; + +console.log(invert(sports)); + +// test("when 'invert' passed an object it returns the object with keys & values swapped.", () => { +// expect(invert(sports)).toEqual({ +// ball: "soccer", +// racket: "tennis", +// hoopBall: "basketball", +// bat: "baseball", +// goggles: "swimming", +// }); +// }); + +