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
2 changes: 1 addition & 1 deletion Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ const address = {
postcode: "XYZ 123",
};

console.log(`My house number is ${address[0]}`);
console.log(`My house number is ${address.houseNumber}`);
4 changes: 3 additions & 1 deletion Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
// Predict and explain first...
// The author variable is an object. As such, it is not iterable by default.
// Therefore, using a for...of loop on it throws a TypeError.

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

for (const value of author) {
for (const value of Object.values(author)) {
console.log(value);
}
14 changes: 10 additions & 4 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
// Predict and explain first...
// The recipe object is interpolated into the template literal (${recipe}).
// During interpolation, JavaScript converts the object to a string.
// Consequently, the object's properties, including the ingredients array, is not displayed.

// This program should log out the title, how many it serves and the ingredients.
// Each ingredient should be logged on a new line
// Each ingredient should be logged on a new line.
// How can you fix it?

const recipe = {
Expand All @@ -10,6 +13,9 @@ const recipe = {
ingredients: ["olive oil", "tomatoes", "salt", "pepper"],
};

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

for (const ingredient of recipe.ingredients) {
console.log(ingredient);
}
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, property) {
if (obj === null || typeof obj !== "object" || Array.isArray(obj)) {
return false;
}
return Object.hasOwn(obj, property);
}

module.exports = contains;
19 changes: 19 additions & 0 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,23 @@
const contains = require("./contains.js");
test("contains on empty object returns false", () => {
expect(contains({}, "a")).toBe(false);
});

test("returns true for existing property", () => {
const obj = { a: 1, b: 2 };
expect(contains(obj, "a")).toBe(true);
});

test("returns false for non-existent property", () => {
const obj = { a: 1, b: 2 };
expect(contains(obj, "c")).toBe(false);
});

test("invalid inputs (arrays, null, non-objects) return false", () => {
expect(contains([], "0")).toBe(false);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Array in JS is also an object, but "0" is not a key of [].

A function that fails to check if the first argument is an array could also return false simply because "0" is not a key of an empty array. To properly test if the function could return false when the first argument is an array, we should use a non-empty array, and then specify a key which the array has as the 2nd argument.

expect(contains(null, "a")).toBe(false);
expect(contains(42, "a")).toBe(false);
});

/*
Implement a function called contains that checks an object contains a
Expand Down
16 changes: 14 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
function createLookup() {
// implementation here
function createLookup(countryCurrencyPairs) {
const lookup = {};

if (!Array.isArray(countryCurrencyPairs)) return lookup;

countryCurrencyPairs.forEach((pair) => {
if (!Array.isArray(pair)) return;
if (pair.length < 2) return;
const [country, currency] = pair;
if (country == null || currency == null) return;
lookup[country] = currency;
});

return lookup;
}

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

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

test("empty input returns empty object", () => {
expect(createLookup([])).toEqual({});
});

test("ignores malformed pairs and only maps valid 2-item arrays", () => {
const pairs = [["GB", "GBP"], ["X"], null, ["FR", "EUR"]];
const expected = { GB: "GBP", FR: "EUR" };
expect(createLookup(pairs)).toEqual(expected);
});

/*

Expand Down
40 changes: 35 additions & 5 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,43 @@
function parseQueryString(queryString) {
const queryParams = {};
if (queryString.length === 0) {

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

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

for (const pair of pairs) {
if (pair === "") {
continue;
}

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

let key;
let value;

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

key = key.replace(/\+/g, " ");
value = value.replace(/\+/g, " ");

key = decodeURIComponent(key);
value = decodeURIComponent(value);

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

return queryParams;
Expand Down
10 changes: 0 additions & 10 deletions Sprint-2/implement/querystring.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,3 @@ test("should replace '+' by ' '", () => {
"full name": "John Doe",
});
});

// 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",
});
});
14 changes: 13 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
function tally() {}
function tally() {
const counts = {};
Comment thread
cjyuan marked this conversation as resolved.

for (const item of items) {
if (!Object.hasOwn(counts, item)) {
counts[item] = 1;
} else {
counts[item]++;
}
}

return counts;
}

module.exports = tally;
14 changes: 13 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,24 @@ 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({});
});

// Given an array with duplicate items
// When passed to tally
// Then it should return counts for each unique item

test("counts duplicates correctly", () => {
expect(tally(["a"])).toEqual({ a: 1 });
expect(tally(["a", "a", "a"]).a).toBe(3);
Comment on lines +35 to +36

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could you research the trade-off between the first and the 2nd approaches to check if the function counts duplicates correctly?

expect(tally(["a", "a", "b", "c"])).toEqual({ a: 2, b: 1, c: 1 });
});

// Given an invalid input like a string
// When passed to tally
// Then it should throw an error
test("throws on invalid input", () => {
expect(() => tally("not-an-array")).toThrow();
expect(() => tally(null)).toThrow();
});
25 changes: 18 additions & 7 deletions Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,31 @@ function invert(obj) {
const invertedObj = {};

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

return invertedObj;
}

// a) What is the current return value when invert is called with { a : 1 }
console.log("invert.js loaded");

// b) What is the current return value when invert is called with { a: 1, b: 2 }
module.exports = invert;

// c) What is the target return value when invert is called with {a : 1, b: 2}
// a) What is the current return value when invert is called with {a : 1}?
// The current return value when invert is called with {a: 1} is {key: 1}.

// c) What does Object.entries return? Why is it needed in this program?
// b) What is the current return value when invert is called with {a: 1, b: 2}?
// The current return value when invert is called with {a: 1, b: 2} is {key: 2}.

// d) Explain why the current return value is different from the target output
// c) What is the target return value when invert is called with {a: 1, b: 2}?
// The target return value when invert is called with {a: 1, b: 2} is {1: a, 2: b}.

// e) Fix the implementation of invert (and write tests to prove it's fixed!)
// d) What does Object.entries return? Why is it needed in this program?
// Object.entries() returns an array containing the key-value pairs of an object.
// It is needed in this program because the function must access both the keys and the values in order to swap them.

// e) Explain why the current return value is different from the target output.
// The current return value is different from the target output because invertedObj.key = value does not use the variable key as the property name.
// Bracket notation is needed to swap the keys and values.

// f) Fix the implementation of invert (and write tests to prove it's fixed!)
18 changes: 18 additions & 0 deletions Sprint-2/interpret/invert.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const invert = require("./invert.js");

test("should swap keys and values in an object", () => {
expect(invert({ a: 1, b: 2 })).toEqual({
1: "a",
2: "b",
});
});

test("should invert an object with a single key-value pair", () => {
expect(invert({ x: 10 })).toEqual({
10: "x",
});
});

test("should return an empty object when passed an empty object", () => {
expect(invert({})).toEqual({});
});
Loading