Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
12 changes: 7 additions & 5 deletions Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
// Predict and explain first...
/* Predict and explain first...

// This code should log out the houseNumber from the address object
// but it isn't working...
// Fix anything that isn't working
My prediction is that when I run this code it will return undefined.
This is because this is an object not an array, objects are not indexed by numbers, they are indexed by keys.
So when i try to access address[0], it will return undefined because there is no key '0' in the address object.

*/

const address = {
houseNumber: 42,
Expand All @@ -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}`);
11 changes: 6 additions & 5 deletions Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// Predict and explain first...

// 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
/* Predict and explain first...
I think this will return an error because of the for...of loop.
The for...of loop is used to iterate over iterable objects like arrays, strings, maps, sets, etc.
So this will return an error because the author object is not iterable.
*/

const author = {
firstName: "Zadie",
Expand All @@ -11,6 +12,6 @@ const author = {
alive: true,
};

for (const value of author) {
for (const value of Object.values(author)) {
console.log(value);
}
16 changes: 10 additions & 6 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
// Predict and explain first...
/* Predict and explain first...

// 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?
This code will log the title and serves correctly, but the ingredients will not be logged on separate lines as intended.
This happens because the ingredients array is being logged as a whole object, which will not format it correctly.
The output will for the ingredients will be [object Object] instead of each ingredient on a new line.

*/

const recipe = {
title: "bruschetta",
Expand All @@ -11,5 +13,7 @@ const recipe = {
};

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
ingredients:`);
recipe.ingredients.forEach((ingredient) => {
console.log(`- ${ingredient}`);
});
8 changes: 6 additions & 2 deletions Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
function contains() {}

function contains(obj, prop) {
if (typeof obj !== "object" || obj === null) {
return false;
}
return obj.hasOwnProperty(prop);
}
module.exports = contains;
43 changes: 30 additions & 13 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,33 @@ 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");

// Given an object with properties
// When passed to contains with an existing property name
// Then it should return true

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

// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error
describe("contains", () => {
test("return false when passed an empty object", () => {
expect(contains({}, "a")).toEqual(false);
});

// Given an object with properties
// When passed to contains with an existing property name
// Then it should return true
test("return true when passed an object with an existing property name", () => {
expect(contains({ a: 1, b: 2 }, "a")).toEqual(true);
expect(contains({ apple: 1, banana: 2 }, "banana")).toEqual(true);
});

// Given an object with properties
// When passed to contains with a non-existent property name
// Then it should return false
test("return false when passed an object with a non-existent property name", () => {
expect(contains({ a: 1, b: 2 }, "c")).toEqual(false);
expect(contains({ apple: 1, banana: 2 }, "orange")).toEqual(false);
});

// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error
test("return false when passed invalid parameters like an array", () => {
expect(contains([], "a")).toEqual(false);
expect(contains(null, "a")).toEqual(false);
expect(contains(undefined, "a")).toEqual(false);
});
});
12 changes: 10 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
function createLookup() {
// implementation here
function createLookup(countryCurrencyPairs) {
if (!Array.isArray(countryCurrencyPairs)) {
throw new Error("Invalid input");
}

const lookup = {};
for (const [country, currency] of countryCurrencyPairs) {
lookup[country] = currency;
}
return lookup;
}

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

test.todo("creates a country currency code lookup for multiple codes");
describe("createLookup", () => {
test("creates a country currency code lookup for a single code", () => {
const countryCurrencyPairs = [["US", "USD"]];
const expectedLookup = { US: "USD" };
expect(createLookup(countryCurrencyPairs)).toEqual(expectedLookup);
});

test("creates a country currency code lookup for multiple codes", () => {
const countryCurrencyPairs = [
["US", "USD"],
["CA", "CAD"],
];
const expectedLookup = { US: "USD", CA: "CAD" };
expect(createLookup(countryCurrencyPairs)).toEqual(expectedLookup);
});

test("returns an empty object when passed an empty array", () => {
const countryCurrencyPairs = [];
const expectedLookup = {};
expect(createLookup(countryCurrencyPairs)).toEqual(expectedLookup);
});

test("throws error for invalid input", () => {
expect(() => createLookup(null)).toThrow();
expect(() => createLookup(undefined)).toThrow();
expect(() => createLookup({})).toThrow();
});

test("returns repeated keys with the last value", () => {
const countryCurrencyPairs = [
["US", "USN"],
["CA", "CAD"],
["US", "USD"],
];
const expectedLookup = { US: "USD", CA: "CAD" };
expect(createLookup(countryCurrencyPairs)).toEqual(expectedLookup);
});
});

/*

Expand Down
11 changes: 10 additions & 1 deletion Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,18 @@ function parseQueryString(queryString) {
return queryParams;
}
const keyValuePairs = queryString.split("&");
const replacePlusWithSpace = (str) => str.replace(/\+/g, " ");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What are you doing with this replacement?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added this replacement to convert all + characters into spaces. One of the tests checks this behaviour, and since decodeURIComponent doesn’t handle +, this step is required to pass the test.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good explanation, the task is complete now


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

const [rawKey, ...rawValueParts] = pair.split("=");
const keyWithSpaces = replacePlusWithSpace(rawKey || "");
const valueWithSpaces = replacePlusWithSpace(rawValueParts.join("=") || "");

const key = decodeURIComponent(keyWithSpaces);
const value = decodeURIComponent(valueWithSpaces);

queryParams[key] = value;
}

Expand Down
12 changes: 3 additions & 9 deletions 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 Down Expand Up @@ -37,12 +37,6 @@ test("should replace '+' by ' '", () => {
});
});

// Stretch exercise: Handling query strings that contain identical keys

// Delete this test if you are not working on this optional case
test("should store values of a key in an array when the key has 2 or more values", () => {
expect(parseQueryString("key=value1&key=value2&key=value3&foo=bar")).toEqual({
key: ["value1", "value2", "value3"],
foo: "bar",
});
test("should handle duplicate keys", () => {
expect(parseQueryString("a=1&a=2")).toEqual({ a: "2" });
});
12 changes: 11 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
function tally() {}
function tally(items) {
if (!Array.isArray(items)) {
throw new Error("Invalid input");
}

const counts = {};
for (const item of items) {
counts[item] = (counts[item] || 0) + 1;
}
return counts;
}

module.exports = tally;
43 changes: 30 additions & 13 deletions Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,38 @@ const tally = require("./tally.js");
* tally(['a', 'a', 'b', 'c']), target output: { a : 2, b: 1, c: 1 }
*/

// Acceptance criteria:

// Given a function called tally
// When passed an array of items
// Then it should return an object containing the count for each unique item

// 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");
describe("tally", () => {
test("returns an empty object for an empty array", () => {
expect(tally([])).toEqual({});
});

// Given an array with duplicate items
// When passed to tally
// Then it should return counts for each unique item
// Given an array with duplicate items
// When passed to tally
// Then it should return counts for each unique item
test("returns counts for each unique item", () => {
expect(tally(["apple"])).toEqual({ apple: 1 });
expect(tally(["apple", "banana", "orange"])).toEqual({
apple: 1,
banana: 1,
orange: 1,
});
});

// Given an invalid input like a string
// When passed to tally
// Then it should throw an error
test("returns counts for each unique item with duplicates", () => {
expect(
tally(["apple", "banana", "orange", "apple", "banana", "orange"])
).toEqual({ apple: 2, banana: 2, orange: 2 });
});

// Given an invalid input like a string
// When passed to tally
// Then it should throw an error
test("throws an error for invalid input", () => {
expect(() => tally("invalid input")).toThrow("Invalid input");
expect(() => tally(123)).toThrow("Invalid input");
expect(() => tally({})).toThrow("Invalid input");
});
});
26 changes: 24 additions & 2 deletions Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,46 @@

// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}

function invert(obj) {
/*function invert(obj) {
const invertedObj = {};

for (const [key, value] of Object.entries(obj)) {
invertedObj.key = value;
}

return invertedObj;
}
}*/

// 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 }
// { 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?
// Object.entries returns an array of key-value pairs from the object. It's needed to iterate over the object's properties.

// d) Explain why the current return value is different from the target output
/*The current return value is different from the target output because the code is incorrectly using `invertedObj.key`
instead of using the actual key and value from the object. It should be using `invertedObj[value] = key;` to correctly
swap the keys and values.*/

// e) Fix the implementation of invert (and write tests to prove it's fixed!)
function invert(obj) {
const invertedObj = {};

if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
throw new Error("Invalid input");
}

for (const [key, value] of Object.entries(obj)) {
invertedObj[value] = key;
}

return invertedObj;
}

module.exports = invert;
24 changes: 24 additions & 0 deletions Sprint-2/interpret/invert.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const invert = require("./invert");

describe("invert", () => {
test("returns an empty object for an empty object", () => {
expect(invert({})).toEqual({});
});

test("returns inverted object for a single key-value pair", () => {
expect(invert({ a: 1 })).toEqual({ 1: "a" });
});

test("returns inverted object for multiple key-value pairs", () => {
expect(invert({ a: 1, b: 2 })).toEqual({ 1: "a", 2: "b" });
});

test("throws an error for invalid input", () => {
expect(() => invert(null)).toThrow("Invalid input");
expect(() => invert("Number")).toThrow("Invalid input");
expect(() => invert(123)).toThrow("Invalid input");
});
test("returns last key for duplicate values", () => {
expect(invert({ a: 1, b: 2, c: 1 })).toEqual({ 1: "c", 2: "b" });
});
});
17 changes: 17 additions & 0 deletions Sprint-2/stretch/count-words.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,20 @@

3. Order the results to find out which word is the most common in the input
*/

function countWords(str) {
if (typeof str !== "string") {
throw new Error("Invalid input");
}

str = str.replace(/[.,!?]/g, "");
str = str.toLowerCase();
const words = str.split(" ").filter(Boolean);
const result = {};

for (const word of words) {
result[word] = (result[word] || 0) + 1;
}
const sortedResult = Object.entries(result).sort((a, b) => b[1] - a[1]);
return sortedResult;
}
Loading
Loading