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
8 changes: 6 additions & 2 deletions Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
// Predict and explain first...
// Prediction:
// The code will print "My house number is undefined"
// because address[0] does not exist.
// Objects use keys like address.houseNumber, not numbers.

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

console.log(`My house number is ${address[0]}`);
// Use the correct key of the object
console.log(`My house number is ${address.houseNumber}`);
7 changes: 4 additions & 3 deletions Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
// Predict and explain first...

//The code will give an error because for...of does not work on objects.
// 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

/*This is because for...of only works with arrays or strings.
An object like author is not an array, so the code will give an error. Nothing will be printed.*/
const author = {
firstName: "Zadie",
lastName: "Smith",
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);
}
6 changes: 4 additions & 2 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Predict and explain first...
/*The code will show [object Object] instead of the ingredients because it tries to print the whole object as a string.*/

// 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 @@ -11,5 +12,6 @@ const recipe = {
};

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

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

return Object.prototype.hasOwnProperty.call(obj, key);
}

module.exports = contains;
19 changes: 18 additions & 1 deletion Sprint-2/implement/contains.test.js
Copy link
Contributor

Choose a reason for hiding this comment

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

Have you run this script to test your function implementation?

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");

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("contains returns true for existing property", () => {
const obj = { a: 1, b: 2 };
expect(contains(obj, "a")).toBe(true);
});


// Given an object with properties
// When passed to contains with a non-existent property name
// Then it should return false
test("contains returns false for non-existent property", () => {
const obj = { a: 1, b: 2 };
expect(contains(obj, "c")).toBe(false);
});


// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error
test("contains returns false for invalid input", () => {
expect(contains([], "length")).toBe(false);
expect(contains(null, "a")).toBe(false);
expect(contains("string", "a")).toBe(false);
});
13 changes: 11 additions & 2 deletions Sprint-2/implement/lookup.js
Copy link
Contributor

Choose a reason for hiding this comment

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

Can this script even run?

Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
function createLookup() {
// implementation here
function createLookup(pairs) {
const lookup = {};

for (let i = 0; i < pairs.length; i++) {
const pair = pairs[i];
const country = pair[0];
const currency = pair[1];
lookup[country] = currency;
}

return lookup;
}

module.exports = createLookup;
11 changes: 11 additions & 0 deletions Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,14 @@ It should return:
'CA': 'CAD'
}
*/

test("creates a country currency code lookup for multiple codes", () => {
const countryCurrencyPairs = [['US', 'USD'], ['CA', 'CAD'], ['GB', 'GBP']];
const result = createLookup(countryCurrencyPairs);

expect(result).toEqual({
'US': 'USD',
'CA': 'CAD',
'GB': 'GBP'
});
});
17 changes: 15 additions & 2 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
function parseQueryString(queryString) {
const queryParams = {};
if (queryString.length === 0) {
if (!queryString) {
return queryParams;
}

function decodePart(text) {
try {
return decodeURIComponent(text);
} catch (error) {
return text;
}
}

const keyValuePairs = queryString.split("&");

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
const index = pair.indexOf("="); // find the first =
if (index === -1) continue; // skip if no =

const key = decodePart(pair.substring(0, index)); // before the =
const value = decodePart(pair.substring(index + 1)); // after the =
queryParams[key] = value;
Copy link
Contributor

Choose a reason for hiding this comment

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

In real query string, both key and value are percent-encoded or URL encoded.
For example,

tags%5B%5D=hello%20world -> key is tags[], value is hello world

Can your function handle URL-encoded query string?

Suggestion: Look up "How to decode a URL-encoded string in JavaScript".

}

Expand Down
22 changes: 22 additions & 0 deletions Sprint-2/implement/querystring.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,25 @@ test("parses querystring values containing =", () => {
"equation": "x=y+1",
});
});

test("parses empty query string", () => {
expect(parseQueryString("")).toEqual({});
});

test("parses multiple key-value pairs", () => {
expect(parseQueryString("a=1&b=2")).toEqual({ a: "1", b: "2" });
});

test("parses key with empty value", () => {
expect(parseQueryString("foo=")).toEqual({ foo: "" });
});

test("parses empty key with value", () => {
expect(parseQueryString("=bar")).toEqual({ "": "bar" });
});

test("parses url encoded key and value", () => {
expect(parseQueryString("tags%5B%5D=hello%20world")).toEqual({
"tags[]": "hello world",
});
});
21 changes: 20 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
function tally() {}
function tally(arr) {
if (!Array.isArray(arr)) {
throw new Error("Input must be an array");
}

const counts = Object.create(null);

for (let i = 0; i < arr.length; i++) {
const item = arr[i];


if (Object.prototype.hasOwnProperty.call(counts, item)) {
counts[item] += 1;
} else {
counts[item] = 1;
}
}

return counts;
}

module.exports = tally;
17 changes: 16 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(Object.create(null));
});

// Given an array with duplicate items
// When passed to tally
// Then it should return counts for each unique item
test("tally on an empty array returns an empty object", () => {
expect(tally([])).toEqual(Object.create(null));
});

test("tally counts keys like toString", () => {
const expected = Object.create(null);
expected.toString = 2;
expect(tally(["toString", "toString"])).toEqual(expected);
});


// Given an invalid input like a string
// When passed to tally
// Then it should throw an error
test("tally throws error for invalid input", () => {
expect(() => tally("not an array")).toThrow("Input must be an array");
});
42 changes: 41 additions & 1 deletion Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,64 @@

// 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;
}*/

//fixed code:
function invert(obj) {
const invertedObj = {};

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

return invertedObj;
}

module.exports = invert;

// 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(obj) returns an array of [key, value] pairs.
Needed because we want to loop through keys and values at the same time.*/

// d) Explain why the current return value is different from the target output

/*Because the code is wrong in one place:

invertedObj.key = value;


This uses the word "key" as a property name instead of using the variable key.

So instead of creating:

{ 1: "a" }


it always creates:

{ key: 1 }


and for multiple items, it keeps overwriting the same "key" */


// e) Fix the implementation of invert (and write tests to prove it's fixed!)
// I did write upt there.