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
5 changes: 4 additions & 1 deletion Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
// Predict and explain first...

// It will print undefined because address[0] looks for a property named "0", which doesn't exist in the object.
// We can use dot notation (address.houseNumber) to access the correct property.

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

console.log(`My house number is ${address[0]}`);
console.log(`My house number is ${address.houseNumber}`);
3 changes: 2 additions & 1 deletion Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Predict and explain first...
// TypeError because object is not iterable and using for of loop in the same way like with arrays won't give us the expected result.

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

for (const value of author) {
for (const value of Object.values(author)) {
console.log(value);
}
7 changes: 5 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...
//It won't print ingredients in the new line as we did not located it and we have to use for loop on an array to log it on new lines.

// 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,7 @@ const recipe = {
};

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

module.exports = contains;
24 changes: 23 additions & 1 deletion Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,43 @@ as an array isn't an object
// When passed an object and a property name
// Then it should return true if the object contains the property, false otherwise

test("when passed an object and a property name, should return true", () => {
expect(contains({ name: "Bart" }, "name")).toBe(true);
});

// Given an empty object
// When passed to contains
// Then it should return false
test.todo("contains on empty object returns false");
test("when passed empty object to contains returns false", () => {
expect(contains({}, "name")).toBe(false);
});

// Given an object with properties
// When passed to contains with an existing property name
// Then it should return true
test("when passed to contains with an existing property name, should return true", () => {
expect(contains({ name: "Bart", age: 28 }, "age")).toBe(true);
});

// Given an object with properties
// When passed to contains with a non-existent property name
// Then it should return false
test("when passed to contains with a non-existing property name, should return false", () => {
expect(contains({ name: "Bart" }, "city")).toBe(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")

test("throws an error when passed not an object", () => {
expect(() => contains(33)).toThrow(/^contains requires an object$/);
expect(() => contains("string")).toThrow(/^contains requires an object$/);
expect(() => contains(["an array", "with", "some", "data"])).toThrow(
/^contains requires an object$/
);
expect(() => contains(null)).toThrow(/^contains requires an object$/);
expect(() => contains()).toThrow(/^contains requires an object$/);
});
11 changes: 9 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
function createLookup() {
// implementation here
function createLookup(pairs) {
const pairsFound = {};
for (const pair of pairs) {
const country = pair[0];
const currency = pair[1];

pairsFound[country] = currency;
}
return pairsFound;
}

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

test.todo("creates a country currency code lookup for multiple codes");
test("creates a country currency code lookup for multiple codes", () => {
const pairs = [
["US", "USD"],
["CA", "CAD"],
];

expect(createLookup(pairs)).toEqual({
US: "USD",
CA: "CAD",
});
});

/*

Expand Down
21 changes: 18 additions & 3 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,25 @@ function parseQueryString(queryString) {
return queryParams;
}
const keyValuePairs = queryString.split("&");

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

const equalsIndex = pair.indexOf("=");
let key;
let value;
if (equalsIndex === -1) {
key = pair;
value = "";
} else {
key = pair.slice(0, equalsIndex);
value = pair.slice(equalsIndex + 1);
}
const decodedKey = decodeURIComponent(key.replaceAll("+", " "));
const decodedValue = decodeURIComponent(value.replaceAll("+", " "));
queryParams[decodedKey] = decodedValue;
}

return queryParams;
Expand Down
12 changes: 1 addition & 11 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 @@ -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",
});
});
15 changes: 14 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
function tally() {}
function tally(array) {
if (!Array.isArray(array)) {
throw new Error("tally requires an array");
}
const unique = {};
for (const arr of array) {
if (Object.hasOwn(unique, arr)) {
unique[arr] += 1;
} else {
unique[arr] = 1;
}
}
return unique;
}

module.exports = tally;
22 changes: 21 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,36 @@ const tally = require("./tally.js");
// 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("when given an array of items, should return object with count of each duplicate items", () => {
expect(tally(["b", "a", "b"])).toEqual({
a: 1,
b: 2,
});
});

// 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("given an array with duplicate items, should return counts for each unique item", () => {
expect(tally(["a", "a", "a"])).toEqual({
a: 3,
});
});

// 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")
test("given an invalid input like string, number or no argument at all, should throw error('tally requires an array')", () => {
expect(() => tally("string")).toThrow(/^tally requires an array$/);
expect(() => tally(331)).toThrow(/^tally requires an array$/);
expect(() => tally()).toThrow(/^tally requires an array$/);
expect(() => tally({})).toThrow(/^tally requires an array$/);
expect(() => tally({ a: 3, b: 5 })).toThrow(/^tally requires an array$/);
});
33 changes: 31 additions & 2 deletions Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,52 @@
// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}

function invert(obj) {
if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
throw new Error("input has to be an object");
}
const invertedObj = {};

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

return invertedObj;
}

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 of key-value pairs from an object.
//We need it in this program to loop through the object's properties and access both the keys and values, so we can swap them.

// d) Explain why the current return value is different from the target output
//The current output is different because dot notation creates a property called "key" instead of using the variable.
//Each iteration overwrites the previous value, and the original keys and values are not swapped.
Comment thread
cjyuan marked this conversation as resolved.
Resolved

// e) Fix the implementation of invert (and write tests to prove it's fixed!)
//fixed, should I make a new file with tests or just add them below as I did?

test("when given single input should invert key and value eg. 'a:1', return '1:a' ", () => {
expect(invert({ a: 1 })).toEqual({ 1: "a" });
});

test("when given multiple inputs should invert key and values correctly ", () => {
expect(invert({ a: 1, b: 3 })).toEqual({ 1: "a", 3: "b" });
});
Comment on lines +41 to +48

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.

In this exercise, you only need to interpret the code. Your answers to the questions are good.
The goal is to be able to distinguish the difference between these two syntax:

  • obj[key]
  • obj.key

Tests are optional and you could leave the test code here if you want.

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.

Thanks for explaining CJ. I'll keep the tests in a single file for better access.


test("when given input type of number, should throw error", () => {
expect(() => invert(22)).toThrow(/^input has to be an object$/);
});
test("when given input type of string, should throw error", () => {
expect(() => invert("22")).toThrow(/^input has to be an object$/);
});
test("when given input with different types of than object, should throw error", () => {
expect(() => invert([22, 33, "ppp"])).toThrow(/^input has to be an object$/);
});
Loading