Skip to content

London | ITP-May-25 | Amy-Rose Collins | DG Sprint 2 #645

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Predict and explain first...
/* Objects store data as key-values pairs, they don't have indices like arrays. In the object below, there is no "0" key. So address[0] is undefined and the print out will probably say "My house number is undefined" */

// This code should log out the houseNumber from the address object
// but it isn't working...
Expand All @@ -12,4 +13,4 @@ const address = {
postcode: "XYZ 123",
};

console.log(`My house number is ${address[0]}`);
console.log(`My house number is ${address.houseNumber}.`);
7 changes: 5 additions & 2 deletions Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
// Predict and explain first...
/* Hmmn, I just looked up how for...of loops work, and it says that they are used on iterables. Objects aren't iterable. I think that lines 15&16 will cause an error.
... It did! TypeError: author is not iterable*/

// 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
Expand All @@ -11,6 +13,7 @@ const author = {
alive: true,
};

for (const value of author) {
console.log(value);
for (const key in author) {
console.log(author[key]);
/* author.key doesn't work because you can't use variables with dot notation - it'd literally be looking for the key called "key" in the author object*/
}
10 changes: 7 additions & 3 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
// Predict and explain first...
/* I think the first part of line 14 looks fine, but that ${recipe} might log the whole object rather than specifically the items in the ingredients array
It actually logged [object Object] for ${recipe}. ${x} is similar to doing x.toString(). Doing a string conversion on a whole object returns '[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
Expand All @@ -10,6 +12,8 @@ const recipe = {
ingredients: ["olive oil", "tomatoes", "salt", "pepper"],
};

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
console.log(`${recipe.title}
\n serves: ${recipe.serves}
\n ingredients:
\n ${recipe.ingredients.join(`\n`)}`);

13 changes: 12 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
function contains() {}
function contains(object, searchKey) {

if(typeof searchKey != 'string' && typeof searchKey != 'symbol') {
// throw new Error(`Please enter a valid property to search for.`)
return false;
};

return object.hasOwnProperty(searchKey);
/* ChatGPT told me about potential problems using .hasOwnProperty, but I don't fully understand the fix it was suggesting yet,
-- object.hasOwnProperty.call(obj, searchKey) --
so I'll pin that thought and come back to it later */
}

module.exports = contains;
34 changes: 33 additions & 1 deletion Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,48 @@ 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 emptyObj = {};
const prop3 = 'beans';
expect(contains(emptyObj,prop3)).toEqual(false);
});

const obj = {name: 'Amy-Rose', age: 28, favMusic: 'Smashing Pumpkins', uhOh: 0};

// Given an object with properties
// When passed to contains with an existing property name
// Then it should return true
test("should return true if the object contains the property", () => {
const prop1 = 'favMusic';
expect(contains(obj,prop1)).toEqual(true);
})


// Given an object with properties
// When passed to contains with a non-existent property name
// Then it should return false

test("should return false if the object doesn't contain the property", () => {
const prop2 = 'favColour';
expect(contains(obj,prop2)).toEqual(false);
})


// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error

test("invalid input should return false", () => {
const prop4 = [1,2,3,4];
expect(contains(obj, prop4)).toEqual(false);
})


// Given an object that contains falsey values
// When passed to contains with an existing property
// Then it should still return true

test("for a property that does exist in the object, contains should return true even if the value in the key-value pair is falsey", () => {
const prop5 = 'uhOh';
expect(contains(obj,prop5)).toEqual(true);
})
52 changes: 50 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,53 @@
function createLookup() {
// implementation here
function createLookup(arr) {

arr.forEach((innerArr, outerArrIndex) => {

if(!/^[A-Z]{2}$/i.test(innerArr[0])) {
throw new Error(`Inner arrays must have a country code of length 2 at index 0. Problem at outer array index ${outerArrIndex}.`);
}

if(!/^[A-Z]{3}$/i.test(innerArr[1])) {
throw new Error(`Inner arrays must have a currency code of length 3 at index 1. Problem at outer array index ${outerArrIndex}.`);
}

if(innerArr.length > 2) {
console.warn(`Only the first two items of each inner array will be used to create the object, any other data will be ignored. Inner array at outer array index ${outerArrIndex} contains data which will be ignored.`);
}

// console.warn(`A tricksy extra warning message`); //was used to test that the console.warn() test only passes if the correct warning is given. testing tests?! gee XD

})

return Object.fromEntries(arr);
}

module.exports = createLookup;



/*
// FUNCTION HISTORY - I wanted to practice solving this in different ways to see which is best

// with a while loop

let i =0;
while (i<arr.length) {
if(arr[i].length !== 2) {
throw new Error("Inner arrays must have length 2 to be used for object creation");
};
i++;
}



// with a for...of loop

for (let i of arr) {
if (i.length!==2){
throw new Error("Inner arrays must have length 2 to be used for object creation");
}
}



*/
26 changes: 25 additions & 1 deletion Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,30 @@
const createLookup = require("./lookup.js");

test.todo("creates a country currency code lookup for multiple codes");
test("given an array with inner arrays like [key,value], createLookup should return an object made from the key-value pairs", () => {
const countryCurrency = [['US', 'USD'], ['CA', 'CAD']];
const lookup = {US: 'USD', CA: 'CAD'};
expect(createLookup(countryCurrency)).toEqual(lookup);
});


test("the first item of each inner array should be a two-letter country code. if this is not the case, createLookup should throw an error", () => {
const invalidArr = [['beans, toast'],['CA', 'CAD']]
expect(() => createLookup(invalidArr)).toThrow();
})

test("the second item of each inner array should be a three-letter currency code. if this is not the case, createLookup should throw an error", () => {
const invalidArr = [['beans, toast'],['CA', 'CAD']]
expect(() => createLookup(invalidArr)).toThrow();
})

// would love to hear your thoughts on tests like this. are they useful? what about deliberately writing side effects into a function? not sure what I should google to learn more about these things.
test("any one or multiple inner arrays with length > 2 should cause createLookup to warn the user that any data after inner array index 1 will be ignored during object creation", () => {
const tooLong = [['US','USD'],['CA','CAD','maple syrup']];
const warnSpy = jest.spyOn(console,'warn').mockImplementation(()=>{});
createLookup(tooLong);
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("data will be ignored"));
warnSpy.mockRestore();
})

/*

Expand Down
19 changes: 16 additions & 3 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
function parseQueryString(queryString) {

const queryParams = {};

if (queryString.length === 0) {
return queryParams;
// in: empty string => out: empty object
}
const keyValuePairs = queryString.split("&");

const keyValuePairs = queryString.split("&"); // keyValuePairs is an array containing items like key=value (a pair)

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
queryParams[key] = value;

if (pair.includes("=")) {
firstIndexOfEqualsSign = pair.indexOf("="); // split at first = only so that values can contain =

const key = pair.slice(0,firstIndexOfEqualsSign);
const value = pair.slice(firstIndexOfEqualsSign+1);
queryParams[key] = value; // where there are repeat keys in query string, this causes some data to be lost/overwritten when making the object. rewrite?
}

else {queryParams[pair] = "";} // if the pair doesn't have an = character, it is taken to be a key with an empty value.

}

return queryParams;
Expand Down
61 changes: 58 additions & 3 deletions Sprint-2/implement/querystring.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,63 @@

const parseQueryString = require("./querystring.js")

test("given a queryString with no query parameters, returns an empty object", function () {
const input = "";
const currentOutput = parseQueryString(input);
const targetOutput = {};
expect(currentOutput).toEqual(targetOutput);
});

test("given a queryString with one pair of query params, returns them in object form", function () {
const input = "fruit=banana";
const currentOutput = parseQueryString(input);
const targetOutput = { fruit: "banana" };
expect(currentOutput).toEqual(targetOutput);
});

test("given a queryString with multiple pairs of query params, returns them in object form",() => {
const input = "fruit=banana&music=florence&flavour=umami";
const currentOutput = parseQueryString(input);
const targetOutput = {fruit: "banana", music: "florence", flavour: "umami"};
expect(currentOutput).toEqual(targetOutput);
});


test("parses querystring values containing =", () => {
expect(parseQueryString("equation=x=y+1")).toEqual({
"equation": "x=y+1",
});
expect(parseQueryString("equation=x=y+1")).toEqual({"equation": "x=y+1"});
});


// handles missing "="
test("when = is missing between a key-pair, the text should be interpreted as a key with an empty value", () => {
const missingEquals = "foo&noms=cheese";
const missingEqualsTO = {foo:"", noms:"cheese"};
expect(parseQueryString(missingEquals)).toEqual(missingEqualsTO);
})

// handles missing value
// no extra code was written for this test to pass - .slice("x") will return an empty string if there is nothing after "x"
test(`when a pair is missing a value, queryString should return 'key: ""' for that item`, () => {
const missingValue = "foo=&noms=cheese";
const missingValueTO = {foo:"", noms:"cheese"};
expect(parseQueryString(missingValue)).toEqual(missingValueTO);
})


// handles missing key ("=bar&noms=cheese")
// no extra code was written for this test to pass - .slice("x") will return an empty string if there is nothing before "x"
test(`when a pair is missing a key, queryString should return "":"value" for that item`, () => {
const missingKey = "=bar&noms=cheese";
const missingKeyTO = {"":"bar", noms: "cheese"};
expect(parseQueryString(missingKey)).toEqual(missingKeyTO);
})

//duplicate keys ("x=1&x=2" => {x:2} / last one wins)
// no extra code was written to pass this test - line 19 of the code simply overwrites the old value with the new one
test(`when a queryString contains values assigned to the same key, the last value assigned to that key in the string should be the one that is returned as part of the object`, ()=> {
const repeatKeys = "one=one&two=two&four=notthisone&four=four"
const repeatKeysTO = {one: "one", two: "two", four: "four"};
expect(parseQueryString(repeatKeys)).toEqual(repeatKeysTO);
})


29 changes: 28 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,30 @@
function tally() {}
function tally(arr) {

if(!arr) {throw new Error(`You didn't pass an argument. You must pass an array to tally.`)}

if (!Array.isArray(arr)) {
throw new Error(`Tally can only count occurences of unique items in arrays. You passed it something that isn't an array.`)
}

counter = {};
arr.forEach((item) => {
counter[item] = (counter[item]||0) +1;
});

return counter;
}


/* // .reduce() version. I find this less easy to understand/read

const tally = arr.reduce((acc,item) => {
acc[item] = (acc[item]||0) + 1;
return acc;
}, {});


// arr.reduce(function, initial accumulator value).
// function: fn(accumulator,currentArrayItem)
// .reduce() calls the function once for every item in the array it was called on */

module.exports = tally;
37 changes: 35 additions & 2 deletions Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,49 @@ 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(`when tally is passed an array of items, if should return an object containing the count for each unique item`, () => {
arr = ['a', 'b', 'c'];
targetOutput = {a : 1, b: 1, c: 1};
expect(tally(arr)).toEqual(targetOutput);
})

// 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", () => {
emptyArr = [];
expect(tally(emptyArr)).toEqual({});
});

// Given an array with duplicate items
// When passed to tally
// Then it should return counts for each unique item
test(`when tally is passed an array of items, if should return an object containing the count for each unique item`, () => {
arr = ['a', 'a', 'a', 'b', 'b', 'c'];
targetOutput = {a : 3, b: 2, c: 1};
expect(tally(arr)).toEqual(targetOutput);
})

// Given an invalid input like a string
// When passed to tally
// Then it should throw an error
// Then it should throw an error(
// This already throws a TypeError without adding extra code, but the explanation it gives might not be helpful if someone couldn't see the code for the tally function.
test(`when tally is passed invalid input like a string, it should throw an error`, () => {
invalidInput = 'snowlover';
expect(()=>{tally(invalidInput)}).toThrow();
})

// mixed data types
test("tally counts correctly with mixed data types", () => {
const arr = ['a', 1, 'a', true, 1, false, true];
const expected = { 'a': 2, '1': 2, 'true': 2, 'false': 1 };
expect(tally(arr)).toEqual(expected);
});


// handles empty and 0 values
test("tally handles empty strings and zero values correctly", () => {
const arr = ['', 0, '', 0];
const expected = { '': 2, '0': 2 };
expect(tally(arr)).toEqual(expected);
});
Loading