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
11 changes: 10 additions & 1 deletion Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
// Predict and explain first...
// Prediction:
// I expect the code to output:
// My house number is 42

// Explanation:
// The address object contains a property called houseNumber
// with the value 42. We can access this property using
// dot notation (address.houseNumber) and display it
// inside a template literal using console.log().

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

console.log(`My house number is ${address[0]}`);
console.log(`My house number is ${address.houseNumber}`);
16 changes: 13 additions & 3 deletions Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
// Predict and explain first...
// Prediction:
// I think this code will produce a TypeError because
// a regular JavaScript object 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
// Explanation:
// The for...of loop works with iterable values such as
// arrays and strings, but it cannot loop directly over
// a regular object. We can use Object.values() to access
// all the property values.

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

for (const value of author) {
for (const value of Object.values(author)) {
console.log(value);
}

// author is an object and it is not iterable.
// for...of works with arrays and strings, but not directly with objects.
// We can use for...in to loop through an object's keys.
15 changes: 13 additions & 2 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
// Predict and explain first...
// Prediction:
// I think this code will print the recipe title and the number
// of servings correctly, but it will print [object Object]
// instead of the ingredients.

// Explanation:
// A regular JavaScript object cannot be displayed directly
// as a readable string using template literals.
// We need to access the ingredients property using
// recipe.ingredients.
// We can use join("\n") to print each ingredient on a new 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?
// How can you fix it? The join() method converts an array into a string.

const recipe = {
title: "bruschetta",
Expand All @@ -12,4 +23,4 @@ const recipe = {

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
${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(cont, str) {
if (typeof cont !== "object" || cont === null || Array.isArray(cont)) {
throw new Error("contains requires an object");
}

const keyArray = Object.keys(cont);
for (const item of keyArray) {
if (item === str) {
return true;
}
}
return false;
}
module.exports = contains;
74 changes: 58 additions & 16 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,67 @@ as an array isn't an object

// Acceptance criteria:

// Given a contains function
// When passed an object and a property name
// Then it should return true if the object contains the property, false otherwise

// Given an empty object
// When passed to contains
// Then it should return false
test.todo("contains on empty object returns false");
describe("contains", () => {
test("given an empty object, returns false", function () {
const input = contains({}, "");

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 that you can think of this boundary test case. Well done!

const currentOutput = input;
const targetOutput = false;

// Given an object with properties
// When passed to contains with an existing property name
// Then it should return true
expect(currentOutput).toEqual(targetOutput);
});
// Given a contains function
// When passed an object and a property name
// Then it should return true if the object contains the property, false otherwise
test("given an object, returns true as the object contains a key of 'a'", function () {
const input = contains({ a: 1, b: 2 }, "a");
const currentOutput = input;
const targetOutput = true;

// Given an object with properties
// When passed to contains with a non-existent property name
// Then it should return false
expect(currentOutput).toEqual(targetOutput);
});
// Given an object with properties
// When passed to contains with a non-existent property name
// Then it should return false
test("given an object, returns false when the object does not contain key 'c'", function () {
const input = contains({ a: 1, b: 2 }, "c");
const currentOutput = input;
const targetOutput = false;

// Given a value that isn't an object - an array, a string, a number,
// null, or no argument at all
// When passed to contains
// Then it should throw Error("contains requires an object")
// (careful: typeof [] and typeof null are both "object")
expect(currentOutput).toEqual(targetOutput);
});
// Given a value that isn't an object - an array, a string, a number,
// null, or no argument at all
// When passed to contains
// Then it should throw Error("contains requires an object")
// (careful: typeof [] and typeof null are both "object")
it("throws when given an array", () => {
expect(() => contains(["banana"], "a")).toThrow(
"contains requires an object"
);
});

it("throws when given a number", () => {
expect(() => contains(123, "a")).toThrow("contains requires an object");
});

it("throws when given a string", () => {
expect(() => contains("hello", "a")).toThrow("contains requires an object");
});

it("throws when given null", () => {
expect(() => contains(null, "a")).toThrow("contains requires an object");
});

it("throws when called without an object argument", () => {
expect(() => contains(undefined, "a")).toThrow(
"contains requires an object"
);
});

it("throws when given an empty array", () => {
expect(() => contains([], "a")).toThrow("contains requires an object");
});
Comment on lines +50 to +81

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Since contains() accepts two mandatory arguments, the test cases should have a proper second argument (even the first argument isn't an object).

Also, a string as first argument is missed in the error cases, and please add it as well. Thank you.

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.

Thank you for your feedback. I've updated the test cases to include the second argument in all cases I'll run the tests again to make sure everything works correctly.

});
8 changes: 6 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
function createLookup() {
// implementation here
function createLookup(countryCurrencyPairs) {
const lookUp = {};
for (const item of countryCurrencyPairs) {
lookUp[item[0]] = item[1];
}
return lookUp;
}

module.exports = createLookup;
14 changes: 12 additions & 2 deletions Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
const createLookup = require("./lookup.js");

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

describe("lookup", () => {
test("creates a country currency code lookup for multiple codes", function () {
const input = [
["US", "USD"],
["CA", "CAD"],
];
const currentOutput = createLookup(input);
const targetOutput = { US: "USD", CA: "CAD" };

expect(currentOutput).toEqual(targetOutput);
});
});
/*

Create a lookup object of key value pairs from an array of code pairs
Expand Down
38 changes: 33 additions & 5 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,44 @@
function parseQueryString(queryString) {
const queryParams = {};
const queryParams = Object.create(null);

if (queryString.length === 0) {
return queryParams;
}
const keyValuePairs = queryString.split("&");

const newQueryStr = queryString.replaceAll("+", " ");
const keyValuePairs = newQueryStr.split("&");

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

const separateIndex = pair.indexOf("=");

let key;
let value;

if (separateIndex === -1) {
key = pair;
value = "";
} else {
key = pair.slice(0, separateIndex);
value = pair.slice(separateIndex + 1);
}
key = decodeURIComponent(key);
value = decodeURIComponent(value);

if (Object.hasOwn(queryParams, key)) {
if (Array.isArray(queryParams[key])) {
queryParams[key].push(value);
} else {
queryParams[key] = [queryParams[key], value];
}
} else {
queryParams[key] = value;
}
}

return queryParams;
}

module.exports = parseQueryString;
2 changes: 1 addition & 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 Down
20 changes: 19 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,21 @@
function tally() {}
function tally(arr) {
const tallyObj = Object.create(null);
if (!Array.isArray(arr)) {
throw new Error("tally requires an array");
}
if (arr.length === 0) {
return {};
}
Comment on lines +6 to +8

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

For your future reference, these 3 lines are not needed, because line 2 initialised tallyObj as an empty {}, and the for-of loop in line 11 will not run when arr is empty, which results in empty {} to be returned correctly in line 18.

let key;
let value;
for (const item of arr) {
if (Object.hasOwn(tallyObj, item)) {
tallyObj[item] = tallyObj[item] + 1;
} else {
tallyObj[item] = 1;

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 own property does the {} accumulator get when an input item is "__proto__"? Try tally(["__proto__"]) and compare the result with the requirement to count every item.

To "like" or "dislike" this comment, please follow this link

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.

Good catch! When using {} as the accumulator, __proto__ is treated as a special property rather than a normal own property. This means tally(["__proto__"]) does not correctly count the item. I've fixed this by using Object.create(null) to create an accumulator without a prototype, allowing __proto__ to be counted as a normal key.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

For your future reference, the proper way to fix this AI's review is to use tallyObj.hasOwnProperty(item) which would not modify nor create side effect to the prototype definition.

}
}
return tallyObj;
}

module.exports = tally;
50 changes: 43 additions & 7 deletions Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,48 @@ 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");
describe("contains", () => {
test("tally on an empty array returns an empty object", function () {
const input = tally([]);
const currentOutput = input;
const targetOutput = {};

// Given an array with duplicate items
// When passed to tally
// Then it should return counts for each unique item
expect(currentOutput).toEqual(targetOutput);
});

// Given an invalid input like a string, a number, or no argument at all
// When passed to tally
// Then it should throw Error("tally requires an array")
// 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("tally on aan array of items, returns an object containing the count for each unique item", function () {
expect(tally(["a"])).toEqual({ a: 1 });
expect(tally(["a", "b", "c"])).toEqual({ a: 1, b: 1, c: 1 });
expect(tally(["a", "a", "b", "c"])).toEqual({ a: 2, b: 1, c: 1 });
});

// Given an array with duplicate items
// When passed to tally
// Then it should return counts for each unique item
test("tally with duplicate items returns counts for each unique item", function () {
expect(tally(["a", "a"])).toEqual({ a: 2 });
expect(tally(["a", "a", "b", "b"])).toEqual({ a: 2, b: 2 });
expect(tally(["a", "a", "b", "b", "c", "c"])).toEqual({ a: 2, b: 2, c: 2 });
});
// Given an invalid input like a string, a number, or no argument at all
// When passed to tally
// Then it should throw Error("tally requires an array")
it("throws when given an invalid input like a string, a number, or no argument", () => {
expect(() => tally(123)).toThrow(new Error("tally requires an array"));
expect(() => tally("hello")).toThrow(new Error("tally requires an array"));
expect(() => tally()).toThrow(new Error("tally requires an array"));
});
test("tally handles object prototype property names", function () {
expect(tally(["toString"])).toEqual({ toString: 1 });
expect(tally(["constructor"])).toEqual({ constructor: 1 });
});
test("counts __proto__ correctly", () => {
expect(tally(["__proto__"])).toEqual(
expect.objectContaining({ __proto__: 1 })
);
});
});
15 changes: 12 additions & 3 deletions Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,34 @@
// Then it should swap the keys and values in the object

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

const assert = require("node:assert/strict");
function invert(obj) {
const invertedObj = {};

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

return invertedObj;
}

assert.deepEqual(invert({ a: 1, b: 2 }), { 1: "a", 2: "b" });
console.log(invert({ a: 1, b: 2 }));
// 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 containing the object's key-value pairs.
//[["a", 1], ["b", 2]]
// We use Object.entries() because we need to access both the keys and values of an object so we can swap them.

// d) Explain why the current return value is different from the target output
// because in this line (invertedObj.key = value;) javascript create a property literally called "key
// it does not use the value stored inside the key, in this case we need to use []

// e) Fix the implementation of invert (and write tests to prove it's fixed!)
Loading