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}`);
2 changes: 1 addition & 1 deletion Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ const author = {
alive: true,
};

for (const value of author) {
for (const value of Object.values(author)) {
console.log(value);
}
4 changes: 2 additions & 2 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,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, prop) {
if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
return false;
}

return prop in obj;
Copy link
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.

}

module.exports = contains;
15 changes: 13 additions & 2 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,27 @@ 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")).toEqual(false)
});


// Given an object with properties
// When passed to contains with an existing property name
// Then it should return true
test("contains an object with propery exist, returns true", () =>{
expect(contains({a:1, b:2}, "a")).toEqual(true)
});

// Given an object with properties
// When passed to contains with a non-existent property name
// Then it should return false

test("return false when the property does not exist", () =>{
expect(contains({a:1, b:3}, "c")).toEqual(false)
});
// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error
test("return false when paramters invaliud ", () =>{
expect(contains([], "a")).toEqual(false)
});
Comment on lines +44 to +46
Copy link
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.

12 changes: 10 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
function createLookup() {
// implementation here
function createLookup(countryCurrencyPairs) {
const lookup = {};

for (const [countryCode, countryCurrency] of countryCurrencyPairs) {
lookup[countryCode] = countryCurrency;
}

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
9 changes: 7 additions & 2 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
function parseQueryString(queryString) {
if (queryString.startsWith("?")) {
queryString = queryString.substring(1);
}

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

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

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
queryParams[key] = value;
const [key, ...valueParts] = pair.split("=");
queryParams[key] = valueParts.join("=");
Copy link
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;
Expand Down
27 changes: 25 additions & 2 deletions Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,26 @@
function tally() {}
function tally(arr) {
// invalid input → throw error
if (!Array.isArray(arr)) {
throw new Error("Input must be an array");
}

module.exports = tally;
// empty array → return empty object
if (arr.length === 0) {
return {};
}

const result = {};

// count items
for (const item of arr) {
if (result[item] === undefined) {
result[item] = 1;
} else {
result[item] = result[item] + 1;
}
}
Comment on lines +12 to +21
Copy link
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;
18 changes: 16 additions & 2 deletions Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,31 @@ 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
// Then it should return an object containing the count for each unique ite

// 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(['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("tally throws an error for invalid input", () => {
expect(() => tally("hello")).toThrow();
});
54 changes: 46 additions & 8 deletions Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,63 @@
// Then it should swap the keys and values in the object

// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}

function invert(obj) {
const invertedObj = {};

for (const [key, value] of Object.entries(obj)) {
invertedObj.key = value;
if (invertedObj[value] === undefined) {
invertedObj[value] = key;
} else if (Array.isArray(invertedObj[value])) {
invertedObj[value].push(key);
} else {
invertedObj[value] = [invertedObj[value], key];
}
Comment on lines +12 to +18
Copy link
Contributor

Choose a reason for hiding this comment

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

Good job in recognising the possibility of collision and taking an extra step to address it.

}

return invertedObj;
}

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

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

//{"1": "a", "2": "b"}
// 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, where each pair is stored as an array.
// It is needed in this program so we can loop through both the keys and values of the object at the same time when inverting it.
//it returns an array of arrays, where each inner array is a pair: [key, value].
//The current return value is different from the target output because when multiple keys have
// the same value, they overwrite each other when inverted. This causes some values to be lost.
// e) Fix the implementation of invert (and write tests to prove it's fixed!)
function invert(obj) {
const invertedObj = {};

// d) Explain why the current return value is different from the target output
for (const [key, value] of Object.entries(obj)) {
// Check if the value already exists as a key in our new object
if (invertedObj[value] === undefined) {
// First time seeing this: Save it as a string
invertedObj[value] = key;
} else if (Array.isArray(invertedObj[value])) {
// It's already an array: Add the new key to the list
invertedObj[value].push(key);
} else {
// It's a string: Turn it into an array and add the new key
invertedObj[value] = [invertedObj[value], key];
}
}

// e) Fix the implementation of invert (and write tests to prove it's fixed!)
return invertedObj;
}

// --- CONSOLE TESTS ---
console.log("Test 1 (Simple):", invert({ a: 1 }));
// Expected: { "1": "a" }

console.log("Test 2 (No duplicates):", invert({ x: 10, y: 20 }));
// Expected: { "10": "x", "20": "y" }

console.log("Test 3 (Collision):", invert({ a: 1, b: 1 }));
// Expected: { "1": ["a", "b"] }

console.log("Test 4 (Triple collision):", invert({ a: 1, b: 1, c: 1 }));
// Expected: { "1": ["a", "b", "c"] }
Loading