Skip to content
Open
Show file tree
Hide file tree
Changes from 8 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...

//because this not an array we can not use index to access the value
// we need to use the key name instead

// 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"] }`);
4 changes: 2 additions & 2 deletions Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Predict and explain first...

// for .. of only works with iterable objects like arrays or strings. but author is an object.
// 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 +11,6 @@ const author = {
alive: true,
};

for (const value of author) {
for (const value of Object.values(author)) {//This extracts the values into an array, and arrays ARE iterable, so the loop works.
console.log(value);
}
9 changes: 6 additions & 3 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Predict and explain first...

// if i want to access the ingredients and present each item on a new line i will use \ and the index of each item
// 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?
Expand All @@ -11,5 +11,8 @@ const recipe = {
};

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
ingredients:
${recipe.ingredients[0]}
${recipe.ingredients[1]}
${recipe.ingredients[2]}
${recipe.ingredients[3]}`);
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you figure out an approach that could work for any number of ingredients?

10 changes: 9 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
function contains() {}
function contains(obj, key) {
if (!obj || typeof obj !== "object" || Array.isArray(obj)) {//check if we have an object and makes sure it's not an array
return false;
}
if (Object.keys(obj).length === 0) {
return false;
}
return key in obj;
}

module.exports = contains;
23 changes: 20 additions & 3 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,37 @@ 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 for an existing property", () => {
const obj = { a: 1, b: 2 };
expect(contains(obj, "a")).toBe(true);
});
// 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);
Copy link
Contributor

Choose a reason for hiding this comment

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

Which of the parameters on line 48 is "invalid"?

Copy link
Author

Choose a reason for hiding this comment

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

You’re right — in that test, neither parameter is actually invalid.
[ ] is still an object in JavaScript, and "a" is a valid key, so the test title didn’t match the behaviour.
I’ve now updated the test to use invalid parameters (such as strings, numbers, null, and undefined)

expect(contains(null, "a")).toBe(false);
expect(contains(123, "a")).toBe(false);
expect(contains("hello", "a")).toBe(false);
});
13 changes: 11 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
function createLookup() {
// implementation here
function createLookup(pairs) {
const lookup = {};//start with an empty object

for (const pair of pairs) {
const country = pair[0];// first element is country code
const currency = pair[1];// second element is currency code
Copy link
Contributor

Choose a reason for hiding this comment

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

Could consider using array destructuring syntax to simplify the code on lines 4-6.

Copy link
Author

Choose a reason for hiding this comment

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

Thanks for the feedback!
I’ve updated the loop to use array destructuring so the code is cleaner and easier to read.

lookup[country] = currency;
}

return lookup;

}

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

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

const expected = {
US: "USD",
CA: "CAD",
};

expect(createLookup(input)).toEqual(expected);
});

test("returns an empty object when given an empty array", () => {
expect(createLookup([])).toEqual({});
});

/*

Expand Down
29 changes: 21 additions & 8 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
function parseQueryString(queryString) {
const queryParams = {};
if (queryString.length === 0) {
return queryParams;
const result = {};

if (!queryString) {
return result;
}
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) {
const index = pair.indexOf("="); // find FIRST "="

if (index === -1) {
// no "=" found → key with empty value
result[pair] = "";
} else {
const key = pair.slice(0, index);
const value = pair.slice(index + 1); // everything after "="
result[key] = value;
}
}

return queryParams;
return result;
}




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 a simple key=value pair", () => {
expect(parseQueryString("name=Ali")).toEqual({
name: "Ali",
});
});

test("parses multiple key=value pairs", () => {
expect(parseQueryString("name=Ali&age=30")).toEqual({
name: "Ali",
age: "30",
});
});

test("returns empty object for empty string", () => {
expect(parseQueryString("")).toEqual({});
});

test("handles keys without values", () => {
expect(parseQueryString("flag")).toEqual({
flag: "",
});
});


11 changes: 10 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
function tally() {}
function tally(arr) {
if (!Array.isArray(arr)) {// if it is not array (string or number throw an error message
throw new TypeError("Input must be an array");
}

return arr.reduce((counts, item) => {
counts[item] = (counts[item] || 0) + 1;// loops through the array and count
return counts;
}, {});
}

module.exports = tally;
18 changes: 17 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,27 @@ const tally = require("./tally.js");
// When passed to tally
// Then it should return an empty object
test.todo("tally on an empty array returns an empty object");

test("returns an empty object for an empty array", () => {
expect(tally([])).toEqual({});
});
// Given an array with duplicate items
// When passed to tally
// Then it should return counts for each unique item
test.todo("tally counts each unique item in the array");
test("counts how many times each item appears", () => {
expect(tally(["a", "b", "a", "c", "b", "a"])).toEqual({
a: 3,
b: 2,
c: 1,
});
});
Comment on lines +35 to +41
Copy link
Contributor

Choose a reason for hiding this comment

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

Does tally(["constructor", "constructor"]) return what you expect?

Copy link
Author

Choose a reason for hiding this comment

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

thank you!
tally(["constructor", "constructor"]) didn’t work properly because I was using a normal {} object, so "constructor" clashed with the built-in constructor property.
I used Object.create(null) so "constructor" behaves like normal keys and doesn’t clash with JavaScript’s internal properties.


// Given an invalid input like a string
// When passed to tally
// Then it should throw an error
test.todo("tally throws an error for non-array input");
test("throws an error if input is not an array", () => {
expect(() => tally("not an array")).toThrow(TypeError);
expect(() => tally(123)).toThrow(TypeError);
expect(() => tally({})).toThrow(TypeError);
});
67 changes: 58 additions & 9 deletions Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,73 @@

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

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

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

//return invertedObj;

return invertedObj;
}

// 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}
// c) What is the target return value when invert is called with {a : 1, b: 2}
//the target is to swap keys and values
{
"1": "a",
"2": "b"
}

// c) What does Object.entries return? Why is it needed in this program?

//it returns an arrays of pairs
[
["a", 1],
["b", 2]
]
// it loops through the keys and the value at the same time
// d) Explain why the current return value is different from the target output
Object.entries({ a: 1, b: 2 })
//current return value
[
["a", 1],
["b", 2]
]
//It lets us easily loop through the keys and values

//for (const [key, value] of Object.entries(obj))
//Because you wrote:
//invertedObj.key = value;
//This literally creates a property named "key", not the value of the variable key.
//i need bracket notation:
//invertedObj[value] = key;
//This sets the property using the variable.

// 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;
}
console.log("Test 1:", invert({ a: 1 }));
console.log("Expected: { '1': 'a' }");
console.log("-------------");

console.log("Test 2:", invert({ a: 1, b: 2 }));
console.log("Expected: { '1': 'a', '2': 'b' }");
console.log("-------------");

console.log("Test 3:", invert({}));
console.log("Expected: {}");
console.log("-------------");

module.exports = invert;
Loading