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,4 +1,7 @@
// Predict and explain first...
// The code is trying to access the houseNumber property of the address object using an index, which is not correct.
// In JavaScript, objects are accessed using their property names, not indices.
// To fix this, we should use the property name 'houseNumber' instead of an index.

// This code should log out the houseNumber from the address object
// but it 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}`);
4 changes: 3 additions & 1 deletion Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

// 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
// The code is trying to iterate over the properties of the author object using a for...of loop, which is not correct for objects in JavaScript.
// In JavaScript, objects are not iterable with for...of loops. Instead, we can use a for...in loop to iterate over the property names of the object, and then access the corresponding values.

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

for (const value of author) {
for (const value in author) {
console.log(value);
}
Comment on lines +16 to 18
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.

Does this output "Zadie", "Smith", ... (the value of the properties)?

6 changes: 5 additions & 1 deletion Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
// 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?
/* The issue with the code is that it is trying to log the entire recipe object directly, which will not format the ingredients as desired.
Instead, we need to access the properties of the recipe object and format the output correctly.
We can use template literals to format the string and join the ingredients array with new line characters.
*/

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

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
${recipe.ingredients.join('\n')}`);
5 changes: 3 additions & 2 deletions Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
function contains() {}

function contains(obj, key) {
return key in obj;
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.

Consider the following two approaches for determining if an object contains a property:

  let obj = {}, propertyName = "toString";
  console.log( propertyName in obj );                // true
  console.log( Object.hasOwn(obj, propertyName) );   // false

Which of these approaches suits your needs better?
For more info, you can look up JS "in" operator vs Object.hasOwn.


In addition, the function is expected to return false when the first parameter is an array or is not an object.

}
module.exports = contains;
24 changes: 22 additions & 2 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,40 @@ as the object doesn't contains a key of 'c'
// 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("returns true if the object contains the property, false otherwise", () => {
const obj = { a: 1, b: 2 };

expect(contains(obj, "a")).toBe(true); // existing property
expect(contains(obj, "b")).toBe(true); // existing property
expect(contains(obj, "c")).toBe(false); // non‑existent property
});



// 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 on object with existing property returns true", () => {
expect(contains({a: 1, b: 2}, "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 on object with non-existent property returns false", () => {
expect(contains({a: 1, b: 2}, "c")).toBe(false);
});

// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error
test("contains on invalid parameters returns false", () => {
expect(contains([], "a")).toBe(false);
});
Comment on lines 50 to +55
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.

This test does not yet confirm that the function correctly returns false when the first argument is an array.
This is because contains([], "a") could also return false simply because "a" is not a key of the array.

Arrays are objects, with their indices acting as keys. A proper test should use a non-empty array along with a valid
key to ensure the function returns false specifically because the input is an array, not because the key is missing.

15 changes: 13 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
function createLookup() {
// implementation here
function createLookup(countryCurrencyPairs) {
let lookup ={};
for(let pair of countryCurrencyPairs){
let key = pair[0];
let value = pair[1];
lookup[key] = value;
}
return lookup;



}
Comment on lines +1 to +12
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.

Indentation is off.

Have you installed the prettier VSCode extension and enabled "Format on save/paste" on VSCode,
as recommended in
https://github.com/CodeYourFuture/Module-Structuring-and-Testing-Data/blob/main/readme.md
?




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 countryCurrencyPairs = [['US', 'USD'], ['CA', 'CAD'], ['GB', 'GBP']];
const expectedLookup = {
US: 'USD',
CA: 'CAD',
GB: 'GBP'
};

expect(createLookup(countryCurrencyPairs)).toEqual(expectedLookup);
});


/*

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

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

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

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
const index = pair.indexOf("=");

let key;
let value;

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

queryParams[key] = value;
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.

Note: (No change required)

  • In real query string, both key and value are percent-encoded or URL encoded in the URL.
    For example, the string "5%" is encoded as "5%25". So to get the actual value of "5%25"
    (whether it is a key or value in the query string), we need to call a function to decode it.

  • You can also explore the URLSearchParams API.

}

return queryParams;
}

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

test("parses querystring values containing &", () => {
expect(parseQueryString("equation=x&y=1")).toEqual({
"equation": "x",
"y": "1",
});
});

test("parses querystring values containing & and =", () => {
expect(parseQueryString("equation=x&y=1&formula=a=b+c")).toEqual({
"equation": "x",
"y": "1",
"formula": "a=b+c",
});
});

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

test("parses querystring with no value", () => {
expect(parseQueryString("key")).toEqual({
"key": "",
});
});
20 changes: 18 additions & 2 deletions Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
function tally() {}
function tally(items) {
if (!Array.isArray(items)) {
throw new Error("Input must be an array");
}

module.exports = tally;
const result = {};

for (const item of items) {
if (result[item]) {
result[item]++;
} else {
result[item] = 1;
}
}
Comment on lines +6 to +14
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.

Does the following function call returns the value you expect?

tally(["toString", "toString"]);

Suggestion: Look up an approach to create an empty object with no inherited properties.


return result;
}

module.exports = tally;
15 changes: 14 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,29 @@ 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 counts the frequency of each item in an array", () => {
expect(tally(["a"])).toEqual({ a: 1 });
expect(tally(["a", "a", "a"])).toEqual({ a: 3 });
expect(tally(["a", "a", "b", "c"])).toEqual({ a: 2, 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 counts duplicate items correctly", () => {
expect(tally(["x", "y", "x", "z", "y"])).toEqual({ x: 2, y: 2, z: 1 });
});

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

// 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)) {
Expand All @@ -15,15 +15,42 @@ function invert(obj) {

return invertedObj;
}
*/

// a) What is the current return value when invert is called with { a : 1 }
// the current return value is { key: 1 }

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

// c) What is the target return value when invert is called with {a : 1, b: 2}
// the target return value is { "1": "a", "2": "b" }

// c) What does Object.entries return? Why is it needed in this program?
/* Object.entries returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
In this program, it is needed to iterate over the key-value pairs of the input object so that we can swap them and create the inverted object.
*/

// d) Explain why the current return value is different from the target output
/* The current return value is different from the target output because in the current implementation,
we are assigning the value to a property named "key" in the inverted object,
which means that every key-value pair in the input object will overwrite the same "key" property in the inverted object.
As a result, only the last key-value pair from the input object will be reflected in the inverted object, leading to incorrect output.
To achieve the target output, we need to use the value from the input object as the key in the inverted object and
the key from the input object as the value in the inverted object.
*/

// e) Fix the implementation of invert (and write tests to prove it's fixed!)
function invert(obj) {
const invertedObj = {};

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

return invertedObj;
}



expect(invert({ a: 1, b: 2 })).toEqual({ '1': 'a', '2': 'b' });
Loading