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: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ node_modules
**/.DS_Store
.idea
package-lock.json
mean.test.js
mean.js
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}`);
5 changes: 3 additions & 2 deletions Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Predict and explain first...
// it won't loop over it as if it was an array

// 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) {
console.log(value);
for (let prop in author) {
console.log(author[prop]);
}
5 changes: 3 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 will not print ingredients at all, as the values aren't accessed

// 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,5 @@ 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 (obj === null || typeof obj !== "object" || Array.isArray(obj)) {
throw new Error("contains requires an object");
}

return Object.hasOwn(obj, key);
}

module.exports = contains;
37 changes: 36 additions & 1 deletion Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,53 @@ as an array isn't an object
// Given an empty object
// When passed to contains
// Then it should return false
test.todo("contains on empty object returns false");
test("should return false given an empty object", () => {
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("should return true when the object has the property", () => {
expect(contains({ age: 8, birthYear: 2019 }, "age")).toBe(true);
});

// Given an object with properties
// When passed to contains with a non-existent property name
// Then it should return false
test("should return false given a non-existent property", () => {
expect(contains({ year: 2026, month: "July" }, "a")).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("should throw an error when passed an array", () => {
expect(() => contains([2, 5, 9], "a")).toThrow(
new Error("contains requires an object")
);
});

test("should throw an error when passed a string", () => {
expect(() => contains("sun", "a")).toThrow(
new Error("contains requires an object")
);
});

test("should throw an error when passed a number", () => {
expect(() => contains(9, "a")).toThrow(
new Error("contains requires an object")
);
});

test("should throw an error when passed a null", () => {
expect(() => contains(null, "a")).toThrow(
new Error("contains requires an object")
);
});

test("should throw an error when passed no argument", () => {
expect(() => contains()).toThrow(new Error("contains requires an object"));
});
Comment on lines +55 to +75

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The string, number, null, and missing-argument cases place .toThrow(...) inside the callback, so Jest never receives a toThrow assertion. The null case also passes a string as the object and null as the key.

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

13 changes: 10 additions & 3 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(countryCurrencyPairs) {
const lookup = {};

countryCurrencyPairs.forEach(function (pair) {
const country = pair[0];
const currency = pair[1];
lookup[country] = currency;
});

return lookup;
}
module.exports = createLookup;
9 changes: 8 additions & 1 deletion Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
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", () => {
expect(
createLookup([
["US", "USD"],
["CA", "CAD"],
])
).toEqual({ US: "USD", CA: "CAD" });
});

/*

Expand Down
20 changes: 18 additions & 2 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
function parseQueryString(queryString) {
const queryParams = {};

if (queryString.startsWith("?")) {
queryString = queryString.slice(1);
}

if (queryString.length === 0) {
return queryParams;
}

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

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

const parts = pair.split("=");
const key = parts[0];
const value = parts.slice(1).join("=");

const decodeKey = decodeURIComponent(key.replace(/\+/g, " "));
const decodeValue = decodeURIComponent(value.replace(/\+/g, " "));
Comment on lines +23 to +24

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The regex works fine here. Can you think of something else that would be more readable for a reader who doesn’t want to decode the \+ and the g flag? Have a look at the string methods available on String.prototype and consider whether one of them would do the same job.

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.

could also use the replaceAll. like so:
const decodeKey = decodeURIComponent(key.replaceAll("+", " "));
const decodeValue = decodeURIComponent(value.replaceAll("+", " "));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

That’s correct, well done! replaceAll("+", " ") is easier to read than the regex. Nice that you applied it to both lines.


queryParams[decodeKey] = decodeValue;
}

return queryParams;
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 accept a leading question mark", () => {
expect(parseQueryString("?name=Sam")).toEqual({ name: "Sam" });
});
17 changes: 16 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
function tally() {}
function tally(items) {
if (!Array.isArray(items)) {
throw new Error("tally requires an array");
}

const counts = {};

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

module.exports = tally;
21 changes: 20 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,35 @@ 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("tally returns an object containing the count for each unique item", () => {
expect(tally(["a", "b", "c"])).toEqual({ a: 1, b: 1, c: 1 });
});

// 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("tally returns counts for each unique item", () => {
expect(tally(["o", "o", "l", "m", "m", "m"])).toEqual({ o: 2, l: 1, m: 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("tally throws an error if passed a string", () => {
expect(() => tally("nothing")).toThrow(new Error("tally requires an array"));
});

test("tally throws an error if passed a number", () => {
expect(() => tally(7)).toThrow(new Error("tally requires an array"));
});

test("tally throws an error if not passed anything", () => {
expect(() => tally()).toThrow(new Error("tally requires an array"));
});
16 changes: 9 additions & 7 deletions Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,22 @@ function invert(obj) {
const invertedObj = {};

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

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?

// it returns the object's properties as pairs where each of them contains a key and it's value.
// It's needed here to make key and value pairs accessible (to eventually build an inverted version of the object).
// d) Explain why the current return value is different from the target output

// In invertedObj.key = value the dot means 'use the property literary named 'key'', not the variable key.
// So each loop pass overwrites that same property and the returned object contains only the last value, like {key: 'blue}.
// e) Fix the implementation of invert (and write tests to prove it's fixed!)
12 changes: 12 additions & 0 deletions Sprint-2/interpret/invert.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const invert = require("./invert.js");

test("invert should swap each key and value when passed an object", () => {
expect(invert({ a: "cherry", b: "kiwi" })).toEqual({
cherry: "a",
kiwi: "b",
});
});

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