Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 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
23 changes: 22 additions & 1 deletion Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,27 @@
// but it isn't working...
// Fix anything that isn't working

/*const address = {
houseNumber: 42,
street: "Imaginary Road",
city: "Manchester",
country: "England",
postcode: "XYZ 123",
};

console.log(`My house number is ${address[0]}`);*/

//---------------------------------------------------------------------------------

/*Predict and explain first...
address is an object, not an array.
Objects don’t have numeric indexes like [0].
So address[0] returns undefined.
That’s why the output would be:
My house number is undefined
*/

//Fixed code
const address = {
houseNumber: 42,
street: "Imaginary Road",
Expand All @@ -12,4 +33,4 @@ const address = {
postcode: "XYZ 123",
};

console.log(`My house number is ${address[0]}`);
console.log(`My house number is ${address.houseNumber}`);
28 changes: 27 additions & 1 deletion Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// 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

const author = {
/*const author = {
firstName: "Zadie",
lastName: "Smith",
occupation: "writer",
Expand All @@ -13,4 +13,30 @@ const author = {

for (const value of author) {
console.log(value);
}*/

//------------------------------------------------------------------------------------------

// Prediction and explanation

/*This gives an error because:
author is a plain object
for...of only works with iterables
Objects are not iterable by default
So JavaScript throws:
TypeError: author is not iterable
*/

//fixed code

const author = {
firstName: "Zadie",
lastName: "Smith",
occupation: "writer",
age: 40,
alive: true,
};

for (const value of Object.values(author)) {
console.log(value);
}
41 changes: 39 additions & 2 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,49 @@
// Each ingredient should be logged on a new line
// How can you fix it?

const recipe = {
/*const recipe = {
title: "bruschetta",
serves: 2,
ingredients: ["olive oil", "tomatoes", "salt", "pepper"],
};

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
${recipe}`);*/

//----------------------------------------------------------------------------------------------------------

// Prediction and explanation
/*The output will be:
bruschetta serves 2
ingredients:
[object Object]

The template literal creates a single string.
${recipe.title} is replaced with "bruschetta".
${recipe.serves} is replaced with 2.
${recipe} is an object, so JavaScript must convert it to a string before inserting it into the template literal.
A plain object's default string representation is "[object Object]".

So JavaScript effectively creates this string before passing it to console.log():

bruschetta serves 2
ingredients:
[object Object]

If the goal is to print each ingredient, we need to access the ingredients array (recipe.ingredients) instead of the whole recipe object. */

//Fixed code

const recipe = {
title: "bruschetta",
serves: 2,
ingredients: ["olive oil", "tomatoes", "salt", "pepper"],
};

console.log(`${recipe.title} serves ${recipe.serves} ingredients:`);
recipe.ingredients.forEach(printIngredients);

function printIngredients(item) {
console.log(item);
}
7 changes: 6 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
function contains() {}
function contains(obj, val) {
if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
return false;
}
return Object.keys(obj).includes(val);
}

module.exports = contains;
23 changes: 22 additions & 1 deletion Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
const contains = require("./contains.js");

describe("contains", () => {
test("Returns true if the object contains the key", () => {
expect(contains({ a: 1, b: 2 }, "a")).toEqual(true);
expect(contains({ cat: 1, dog: 2, cow: 2 }, "cow")).toEqual(true);
});

test("Returns false if the object doesn't contain the key", () => {
expect(contains({ a: 1, b: 2 }, "c")).toEqual(false);
expect(contains({ cat: 1, dog: 2, cow: 2 }, "pig")).toEqual(false);
});

test("Returns false if the object is empty", () => {
expect(contains({}, "c")).toEqual(false);
});
test("Returns false if the input is invalid", () => {
expect(contains([1, 2, 3, 4], 3)).toEqual(false);
expect(contains(null, 3)).toEqual(false);
expect(contains("Hello World", "o")).toEqual(false);
});
});

/*
Implement a function called contains that checks an object contains a
particular property
Expand All @@ -20,7 +41,7 @@ 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.todo("contains on empty object returns false");

// Given an object with properties
// When passed to contains with an existing property name
Expand Down
14 changes: 12 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
function createLookup() {
// implementation here
function createLookup(countryCurrencyPairs) {
let newObj = {};
if (!Array.isArray(countryCurrencyPairs)) {
throw new Error("Input must be an array");
}

countryCurrencyPairs.forEach((pair) => {
if (Array.isArray(pair) && pair.length === 2) {
newObj[pair[0]] = pair[1];
}
});
return newObj;
}

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

test.todo("creates a country currency code lookup for multiple codes");
//test.todo("creates a country currency code lookup for multiple codes");

/*

Expand Down Expand Up @@ -33,3 +33,49 @@ It should return:
'CA': 'CAD'
}
*/

describe("createLookup", () => {
test("Return an object with country codes and currency codes", () => {
const input = [
["US", "USD"],
["CA", "CAD"],
];
const output = {
US: "USD",
CA: "CAD",
};
expect(createLookup(input)).toEqual(output);
});
test("Ignores invalid inner array values", () => {
const input = [["US", "USD"], "Hello", ["CA", "CAD"]];
const output = {
US: "USD",
CA: "CAD",
};
expect(createLookup(input)).toEqual(output);
});
test("returns empty object for empty inner arrays", () => {
expect(createLookup([[]])).toEqual({});
});
test("Handle repeat keys", () => {
const input = [
["US", "USD"],
["CA", "CAD"],
["US", "US-Dollar"],
];
const output = {
US: "US-Dollar",
CA: "CAD",
};
expect(createLookup(input)).toEqual(output);
});

test("Throws an error for invalid input", () => {
expect(() => createLookup(null)).toThrow();
expect(() => createLookup("Hello World")).toThrow();
expect(() => createLookup({})).toThrow();
});
test("Return an empty object with empty input", () => {
expect(createLookup([])).toEqual({});
});
});
32 changes: 26 additions & 6 deletions Sprint-2/implement/querystring.js
Comment thread
LonMcGregor marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -1,13 +1,33 @@
function parseQueryString(queryString) {
const queryParams = {};
if (queryString.length === 0) {
return queryParams;
if (typeof queryString !== "string") {
throw new Error("Invalid input");
}
const keyValuePairs = queryString.split("&");
if (queryString.length === 0) return queryParams;

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
queryParams[key] = value;
const parseQueryStringArray = queryString.replace(/\+/g, " ").split("&");
let key;
let value;
for (const pair of parseQueryStringArray) {
if (pair === "") continue;
let equalIndex = pair.indexOf("=");
if (equalIndex === -1) {
key = pair;
value = "";
} else {
key = decodeURIComponent(pair.slice(0, equalIndex));
value = decodeURIComponent(pair.slice(equalIndex + 1));
}
if (Object.hasOwn(queryParams, key)) {
if (Array.isArray(queryParams[key])) {
queryParams[key].push(value);
} else {
queryParams[key] = [queryParams[key]];
queryParams[key].push(value);
}
} else {
queryParams[key] = value;
}
}

return queryParams;
Expand Down
32 changes: 31 additions & 1 deletion Sprint-2/implement/querystring.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// Below are some test cases the implementation doesn't handle well.
// Fix the implementation for these tests, 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("should parse values containing '='", () => {
expect(parseQueryString("equation=a=b-2")).toEqual({
Expand All @@ -25,6 +25,36 @@ test("should accept empty string as key or as value", () => {
expect(parseQueryString("=")).toEqual({ "": "" });
});

test("should return empty object for empty input", () => {
expect(parseQueryString("")).toEqual({});
});

test("throws an error for invalid input", () => {
expect(() => parseQueryString(null)).toThrow("Invalid input");
expect(() => parseQueryString({})).toThrow("Invalid input");
expect(() => parseQueryString([])).toThrow("Invalid input");
expect(() => parseQueryString(undefined)).toThrow("Invalid input");
expect(() => parseQueryString(123)).toThrow("Invalid input");
expect(() => parseQueryString(true)).toThrow("Invalid input");
});

test("should work on duplicate empty keys", () => {
expect(parseQueryString("=one&=two")).toEqual({
"": ["one", "two"],
});
});
test("should work on duplicate empty values", () => {
expect(parseQueryString("key=&key=")).toEqual({
key: ["", ""],
});
});

test("should work on & inside values", () => {
expect(parseQueryString("text=Tom%26Jerry")).toEqual({
text: "Tom&Jerry",
});
});

test("should decode percent-encoded characters", () => {
expect(parseQueryString("%24half=1%2F2")).toEqual({
$half: "1/2",
Expand Down
12 changes: 10 additions & 2 deletions Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
function tally() {}

function tally(input) {
const obj = {};
if (input === null || !Array.isArray(input)) {
throw new Error("Invalid input");
}
input.forEach((el) => {
obj[el] = (obj[el] || 0) + 1;
});
return obj;
}
module.exports = tally;
34 changes: 33 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ 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.todo("tally on an empty array returns an empty object");

// Given an array with duplicate items
// When passed to tally
Expand All @@ -32,3 +32,35 @@ test.todo("tally on an empty array returns an empty object");
// Given an invalid input like a string
// When passed to tally
// Then it should throw an error

describe("tally", () => {
test("Return an empty object for empty array input", () => {
expect(tally([])).toEqual({});
});
test("Return an object containing the count for each unique item", () => {
expect(tally(["cat"])).toEqual({ cat: 1 });
expect(tally(["cat", "dog", "rat", "duck"])).toEqual({
cat: 1,
dog: 1,
rat: 1,
duck: 1,
});
});
test("Return an object containing the count for duplicate items", () => {
expect(tally(["cat", "dog", "rat", "cat", "duck", "dog"])).toEqual({
cat: 2,
dog: 2,
rat: 1,
duck: 1,
});
expect(tally([1, 2, 1])).toEqual({
1: 2,
2: 1,
});
});
test("throws an error for invalid input", () => {
expect(() => tally("Hello World")).toThrow("Invalid input");
expect(() => tally({ cat: 3 })).toThrow("Invalid input");
expect(() => tally(null)).toThrow("Invalid input");
});
});
Loading
Loading