diff --git a/Sprint-2/debug/address.js b/Sprint-2/debug/address.js index 940a6af83..caf72bc2b 100644 --- a/Sprint-2/debug/address.js +++ b/Sprint-2/debug/address.js @@ -1,8 +1,10 @@ // Predict and explain first... +//the original code is using the wrong notation to access our object this will return undefined as we do not have a 0 property. // This code should log out the houseNumber from the address object // but it isn't working... // Fix anything that isn't working +//fixed it by putting "houseNumber" in the square brackets. const address = { houseNumber: 42, @@ -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..d8be5b0b4 100644 --- a/Sprint-2/debug/author.js +++ b/Sprint-2/debug/author.js @@ -1,7 +1,9 @@ // Predict and explain first... +//the method for of is an array method and it would be looking for an indexed list of items rather than a key value pair so an error will be thrown since we are using an object. // 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 +//i can fix this by changing for ... of to for ... in. const author = { firstName: "Zadie", @@ -11,6 +13,6 @@ 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..441885ff0 100644 --- a/Sprint-2/debug/recipe.js +++ b/Sprint-2/debug/recipe.js @@ -1,8 +1,10 @@ // Predict and explain first... +//it will display the title and number of people it serves on one line then the whole recipe on the next 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? +//by using the string literal to ensure multiple lines, then having the title on the first line, the number served on the next line and ingredients on the third line. using the dot notation to access the properties needed. const recipe = { title: "bruschetta", @@ -10,6 +12,15 @@ const recipe = { ingredients: ["olive oil", "tomatoes", "salt", "pepper"], }; -console.log(`${recipe.title} serves ${recipe.serves} - ingredients: -${recipe}`); +//changed console to display for any number of ingredients +console.log(`${recipe.title} serves ${recipe.serves} + ingredients: ${recipe.ingredients[0]} + ${recipe.ingredients[1]} + ${recipe.ingredients[2]} + ${recipe.ingredients[3]}`); + +console.log(`${recipe.title} serves ${recipe.serves} + ingredients:`); +for (let ingredient of recipe.ingredients) { + console.log(` ${ingredient}`); +} diff --git a/Sprint-2/implement/contains.js b/Sprint-2/implement/contains.js index cd779308a..2cea09edd 100644 --- a/Sprint-2/implement/contains.js +++ b/Sprint-2/implement/contains.js @@ -1,3 +1,17 @@ -function contains() {} +function contains(checkObj, checkProp) { + if ( + typeof checkObj === "object" && + checkObj !== null && + !Array.isArray(checkObj) + ) { + if (Object.hasOwn(checkObj, checkProp)) { + return true; + } else { + return false; + } + } else { + throw new Error("error invalid parameter please provide an object"); + } +} module.exports = contains; diff --git a/Sprint-2/implement/contains.test.js b/Sprint-2/implement/contains.test.js index 326bdb1f2..0207c5348 100644 --- a/Sprint-2/implement/contains.test.js +++ b/Sprint-2/implement/contains.test.js @@ -20,16 +20,25 @@ 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", () => + 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 an object contains a property that matches the one passed to contains", () => + expect(contains({ area: "Manchester" }, "area")).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 an object with properties is passed to contains with a non-existent property name", () => + expect(contains({ area: "Manchester" }, "town")).toBe(false)); // Given invalid parameters like an array // When passed to contains // Then it should return false or throw an error +test("should throw an error when when an invalid parameter like an array is passed to contains", () => + expect(() => contains([1, 4, 5], 0)).toThrow( + "error invalid parameter please provide an object" + )); diff --git a/Sprint-2/implement/lookup.js b/Sprint-2/implement/lookup.js index a6746e07f..63fa99cc9 100644 --- a/Sprint-2/implement/lookup.js +++ b/Sprint-2/implement/lookup.js @@ -1,5 +1,20 @@ -function createLookup() { +function createLookup(inputArray) { // implementation here + const returnObject = {}; + + if (!Array.isArray(inputArray)) { + throw new Error("error incorrect parameter passed please provide an array"); + } + + if (inputArray.length === 0) { + return returnObject; + } + + for (let item of inputArray) { + returnObject[item[0]] = item[1]; + } + + return returnObject; } module.exports = createLookup; diff --git a/Sprint-2/implement/lookup.test.js b/Sprint-2/implement/lookup.test.js index 547e06c5a..94e15bf90 100644 --- a/Sprint-2/implement/lookup.test.js +++ b/Sprint-2/implement/lookup.test.js @@ -1,6 +1,25 @@ 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", () => { + expect( + createLookup([ + ["US", "USD"], + ["CA", "CAD"], + ["MW", "MWK"], + ["ZW", "ZWD"], + ]) + ).toEqual({ US: "USD", CA: "CAD", MW: "MWK", ZW: "ZWD" }); +}); + +test("if passed an empty array , should return an empty object", () => { + expect(createLookup([])).toEqual({}); +}); + +test("if passed parameter which is not an array throw an error", () => { + expect(() => createLookup("US, USD")).toThrow( + "error incorrect parameter passed please provide an array" + ); +}); /* diff --git a/Sprint-2/implement/querystring.js b/Sprint-2/implement/querystring.js index 45ec4e5f3..bbcd7b862 100644 --- a/Sprint-2/implement/querystring.js +++ b/Sprint-2/implement/querystring.js @@ -1,13 +1,35 @@ function parseQueryString(queryString) { const queryParams = {}; + if (queryString.length === 0) { return queryParams; } - const keyValuePairs = queryString.split("&"); - for (const pair of keyValuePairs) { - const [key, value] = pair.split("="); - queryParams[key] = value; + if (queryString.includes("&")) { + const keyValuePairs = queryString.split("&"); + + for (const pair of keyValuePairs) { + if (!pair.includes("=")) { + throw new Error( + "error invalid format string, no = to separate key value pairs" + ); + } else { + const keyValuePair = pair.split("="); + console.log(keyValuePair + "the single pair"); + + queryParams[keyValuePair[0]] = keyValuePair[1]; + } + } + } else if (queryString.includes("=")) { + const equalSignIndex = queryString.indexOf("="); + + queryParams[queryString.slice(0, equalSignIndex)] = queryString.slice( + equalSignIndex + 1 + ); + } else { + throw new Error( + "error invalid format string, no = to separate key value pairs" + ); } return queryParams; diff --git a/Sprint-2/implement/querystring.test.js b/Sprint-2/implement/querystring.test.js index 3e218b789..3106254cc 100644 --- a/Sprint-2/implement/querystring.test.js +++ b/Sprint-2/implement/querystring.test.js @@ -3,10 +3,37 @@ // Below is one test case for an edge case the implementation doesn't handle well. // Fix the implementation for this test, and try to think of as many other edge cases as possible - write tests and fix those too. -const parseQueryString = require("./querystring.js") +const parseQueryString = require("./querystring.js"); + +test("parseQueryString receives an empty string", () => { + expect(parseQueryString("")).toEqual({}); +}); + +test("if our function is passed 2 key - value pairs", () => { + expect(parseQueryString("color=brown&width=100")).toEqual({ + color: "brown", + width: "100", + }); +}); test("parses querystring values containing =", () => { expect(parseQueryString("equation=x=y+1")).toEqual({ - "equation": "x=y+1", + equation: "x=y+1", }); }); + +test("if our function is passed only one key - value pair", () => { + expect(parseQueryString("color=brown")).toEqual({ color: "brown" }); +}); + +test("parses querystring without an =, it should throw an error", () => { + expect(() => parseQueryString("colorisequaltobrown")).toThrow( + "error invalid format string, no = to separate key value pairs" + ); +}); + +test("if our function is passed only one string but there is no =", () => { + expect(() => parseQueryString("color,brown")).toThrow( + "error invalid format string, no = to separate key value pair" + ); +}); diff --git a/Sprint-2/implement/tally.js b/Sprint-2/implement/tally.js index f47321812..105a0d15a 100644 --- a/Sprint-2/implement/tally.js +++ b/Sprint-2/implement/tally.js @@ -1,3 +1,37 @@ -function tally() {} +function tally(inputArray) { + if (Array.isArray(inputArray)) { + if (inputArray.length === 0) { + return {}; + } + + let itemCount = 0; + const tallyObject = {}; + let n = 0; + + while (inputArray.length > 0) { + itemCount = 0; + const tempArray = []; + let i = 0; + let currentArrayItem = inputArray[0]; + + while (i < inputArray.length) { + if (currentArrayItem === inputArray[i]) { + itemCount++; + tempArray.push(inputArray.splice(i, 1)); + i--; + } + + if (itemCount > 0) { + tallyObject[currentArrayItem] = itemCount; + } + + i++; + } + } + return tallyObject; + } else { + throw new Error("error invalid input passed, please provide an array"); + } +} module.exports = tally; diff --git a/Sprint-2/implement/tally.test.js b/Sprint-2/implement/tally.test.js index 2ceffa8dd..afc6315aa 100644 --- a/Sprint-2/implement/tally.test.js +++ b/Sprint-2/implement/tally.test.js @@ -23,12 +23,27 @@ 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({}); +}); // Given an array with duplicate items // When passed to tally // Then it should return counts for each unique item +test("given an array with duplicate items it should return counts for each unique item ", () => { + expect(tally(["a", "a", "b", "c", "c", "d", "a"])).toEqual({ + a: 3, + b: 1, + c: 2, + d: 1, + }); +}); // Given an invalid input like a string // When passed to tally // Then it should throw an error +test("should throw an error when tally is passed an invalid input like a string", () => { + expect(() => tally("b,b,c,d,e,e,f")).toThrow( + "error invalid input passed, please provide an array" + ); +}); diff --git a/Sprint-2/interpret/invert.js b/Sprint-2/interpret/invert.js index bb353fb1f..c8e2d7e35 100644 --- a/Sprint-2/interpret/invert.js +++ b/Sprint-2/interpret/invert.js @@ -9,21 +9,41 @@ function invert(obj) { const invertedObj = {}; - for (const [key, value] of Object.entries(obj)) { - invertedObj.key = value; + if (obj !== null && !Array.isArray(obj) && typeof obj === "object") { + for (const [key, value] of Object.entries(obj)) { + if (typeof value != "string" && typeof value !== "number") { + throw new Error( + "error invalid input entered, expecting an object to have only strings as values" + ); + } + + invertedObj[value] = key; + } + } else { + throw new Error("error invalid input entered, expecting an object"); } return invertedObj; } +module.exports = invert; + // a) What is the current return value when invert is called with { a : 1 } +//it returns a string describing the object. // b) What is the current return value when invert is called with { a: 1, b: 2 } +//it returns an object with one key value pair, the key is key and value is 2 // c) What is the target return value when invert is called with {a : 1, b: 2} +//the target return value is {"1": "a", "2": "b"}. // c) What does Object.entries return? Why is it needed in this program? +//it returns an array made up of arrays of the original objects key - value pairs. +//it allows us to unpack the contents of the object into an array which can then be used to create the new object // d) Explain why the current return value is different from the target output +//because we used dot notation to assign a value to our key, this creates a property called key +//and assigns it a value. we want our key to get its name from a variable so we need to use bracket notation. // e) Fix the implementation of invert (and write tests to prove it's fixed!) +//we can fix it by using invertedObj[value] = key. diff --git a/Sprint-2/interpret/invert.test.js b/Sprint-2/interpret/invert.test.js new file mode 100644 index 000000000..cb5c1e144 --- /dev/null +++ b/Sprint-2/interpret/invert.test.js @@ -0,0 +1,28 @@ +const invert = require("./invert.js"); + +describe("tests to see if invert function swaps around the keys and values in a given object", () => { + test("if invert is passed a value which is not an object, it should throw an error", () => { + expect(() => + invert([ + ["x", 10], + ["y", 20], + ]) + ).toThrow("error invalid input entered, expecting an object"); + }); + + test("if we are passed an empty object we should return an empty object", () => { + expect(invert({})).toEqual({}); + }); + + test("given an object with key value pairs, it should swap the keys and values in the object", () => { + expect(invert({ x: 10, y: 20 })).toEqual({ 10: "x", 20: "y" }); + expect( + invert({ city: "Birmingham", population: "345908", boroughs: "20" }) + ).toEqual({ Birmingham: "city", 345908: "population", 20: "boroughs" }); + }); +}); +test("if invert is passed an object which has an array or object as one of its values, it should throw an error", () => { + expect(() => invert({ cars: { toyota: 2, bmw: 1, benz: 4 } })).toThrow( + "error invalid input entered, expecting an object to have only strings as values" + ); +}); diff --git a/Sprint-2/package-lock.json b/Sprint-2/package-lock.json index 9b4c725d6..ceda7296e 100644 --- a/Sprint-2/package-lock.json +++ b/Sprint-2/package-lock.json @@ -56,6 +56,7 @@ "integrity": "sha512-Oixnb+DzmRT30qu9d3tJSQkxuygWm32DFykT4bRoORPa9hZ/L4KhVB/XiRm6KG+roIEM7DBQlmg27kw2HZkdZg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@ampproject/remapping": "^2.2.0", "@babel/code-frame": "^7.25.7", @@ -1368,6 +1369,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "caniuse-lite": "^1.0.30001663", "electron-to-chromium": "^1.5.28", diff --git a/prep/mean.js b/prep/mean.js new file mode 100644 index 000000000..31f463f9c --- /dev/null +++ b/prep/mean.js @@ -0,0 +1,18 @@ +//a data structure is used to group data together. it is a collection of data which has functions which allow you to access and manipulate the data. +//an array is a zero indexed collection of data that holds data in an ordered list. +function calculateMean(list) { + let total = 0; + + for (const item of list) { + total += item; + } +} + +function calculateMedian(list) { + const middleIndex = Math.floor(list.length / 2); + const median = list.splice(middleIndex, 1)[0]; + + return median; +} + +calculateMean([10, 20, 30, 40, 50]); diff --git a/prep/mean.test.js b/prep/mean.test.js new file mode 100644 index 000000000..386732522 --- /dev/null +++ b/prep/mean.test.js @@ -0,0 +1,22 @@ +test("calculates the mean of a list of numbers", () => { + const list = [3, 50, 7]; + const currentOutput = calculateMean(list); + const targetOutput = 20; + + expect(currentOutput).toEqual(targetOutput); +}); + +test("calculates the median of a list of odd length", () => { + const list = [10, 20, 30, 50, 60]; + const currentOutput = calculateMedian(list); + const targetOutput = 30; + + expect(currentOutput).toEqual(targetOutput); +}); + +test("doesn't modify the input", () => { + const list = [1, 2, 3]; + calculateMedian(list); + + expect(list).toEqual([1, 2, 3]); // Note that the toEqual matcher checks the values inside arrays when comparing them - it doesn't use `===` on the arrays, we know that would always evaluate to false. +}); diff --git a/prep/package.json b/prep/package.json new file mode 100644 index 000000000..2301e1638 --- /dev/null +++ b/prep/package.json @@ -0,0 +1,16 @@ +{ + "name": "prep", + "version": "1.0.0", + "description": "", + "main": "mean.js", + "scripts": { + "test": "jest" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "commonjs", + "devDependencies": { + "jest": "^30.2.0" + } +}