Skip to content
10 changes: 9 additions & 1 deletion Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
// Predict and explain first...

//The code is trying to access address[0], but address is an object, not an array.
//Objects use keys (like houseNumber) instead of numeric indices.
//So address[0] is undefined, because there is no property with the key "0".

// 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 +16,8 @@ const address = {
postcode: "XYZ 123",
};

console.log(`My house number is ${address[0]}`);
console.log(`My house number is ${address.houseNumber}`);

// The code is correct and will log "My house number is 42" to the console.

// My house number is 42
7 changes: 6 additions & 1 deletion Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
// Predict and explain first...

//This code tries to use a for...of loop on an object, but objects are not iterable by default.
//for...of works on iterables like arrays, strings, maps, sets — not plain objects.
//Running this will throw:
//TypeError: author is not iterable

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

for (const value of author) {
for (const value of Object.values(author)) {
console.log(value);
}
10 changes: 8 additions & 2 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
// Predict and explain first...
//${recipe} tries to insert the entire object (recipe) directly into the string.
//This will result in something like:[object Object]


// 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 @@ -10,6 +13,9 @@ const recipe = {
ingredients: ["olive oil", "tomatoes", "salt", "pepper"],
};

console.log(`${recipe.title} serves ${recipe.serves}
console.log(`${recipe.title}
serves ${recipe.serves}
ingredients:
${recipe}`);
${recipe.ingredients.join("\n")}`);
//recipe.ingredients is an array: ["olive oil", "tomatoes", "salt", "pepper"]
//.join("\n") turns that array into a string, separating each ingredient with a newline (\n)
10 changes: 8 additions & 2 deletions 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)) {
throw new Error("Invalid input: must be a non-null object");
}

module.exports = contains;
return obj.hasOwnProperty(prop);
}

module.exports = contains;
21 changes: 20 additions & 1 deletion Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,35 @@ 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");

// Empty object should return false
test("contains on empty object returns false", () => {
const result = contains({}, "a");
expect(result).toBe(false); });

// Given an object with properties
// When passed to contains with an existing property name
// Then it should return true

// Object with properties and existing key should return true
test("contains returns true for existing property", () => {
const obj = { a: 1, b: 2 };
const result = contains(obj, "a");
expect(result).toBe(true);
});

// Given an object with properties
// When passed to contains with a non-existent property name
// Then it should return false
test("contains returns false for non-existing property", () => {
const obj = { a: 1, b: 2 };
const result = contains(obj, "c");
expect(result).toBe(false);
});

// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error
test("contains returns false or throws when input is not an object", () => {
const obj = ["a", "b"];
expect(() => contains(["a", "b"], "a")).toThrow(); });
8 changes: 7 additions & 1 deletion Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
function createLookup() {
function createLookup(pairs) {
const lookup= {};
for (let [countryCode, currencyCode] of pairs) {
lookup[countryCode] = currencyCode;
}

return lookup;
// implementation here
}

Expand Down
52 changes: 47 additions & 5 deletions Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,57 @@
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 input = [
['US', 'USD'],
['CA', 'CAD'],
['UK', 'GBP'],
];
const expected = {
US: 'USD',
CA: 'CAD',
UK: 'GBP'
};
expect(createLookup(input)).toEqual(expected);
});

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

test("overwrites value if a country code appears more than once", () => {
const input = [
['UK', 'GBP'],
['UK', 'POUND']
];
expect(createLookup(input)).toEqual({ UK: 'POUND' });
});

test("ignores extra values in pairs", () => {
const input = [
['UK', 'GBP', 'Extra'],
['US', 'USD']
];
expect(createLookup(input)).toEqual({ UK: 'GBP', US: 'USD' });
});

test("ignores invalid pairs (less than two elements)", () => {
const input = [
['UK'], // Invalid
['US', 'USD']
];
expect(createLookup(input)).toEqual({ US: 'USD' });
});


/*

Create a lookup object of key value pairs from an array of code pairs

Acceptance Criteria:

Given
- An array of arrays representing country code and currency code pairs
e.g. [['US', 'USD'], ['CA', 'CAD']]
e.g. [['US', 'USD'], ['CA', 'CAD'],['UK','GBP']]

When
- createLookup function is called with the country-currency array as an argument
Expand All @@ -21,7 +62,7 @@ Then
- The values are the corresponding currency codes

Example
Given: [['US', 'USD'], ['CA', 'CAD']]
Given: [['US', 'USD'], ['CA', 'CAD'], ['UK', 'GPB']]

When
createLookup(countryCurrencyPairs) is called
Expand All @@ -30,6 +71,7 @@ Then
It should return:
{
'US': 'USD',
'CA': 'CAD'
'CA': 'CAD',
'UK': 'GBP'
}
*/
15 changes: 9 additions & 6 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
function parseQueryString(queryString) {
const queryParams = {};
if (queryString.length === 0) {
return queryParams;
}
if (!queryString) return queryParams;

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

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
queryParams[key] = value;
}
const [key, ...rest] = pair.split("="); // Grab everything after first '='
const value = rest.join("="); // Safely join back if value had '=' signs
Copy link
Member

Choose a reason for hiding this comment

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

This joining logic is really useful, but if you removed it none of your tests would start failing. Could you add a test that shows why this logic is here?

Copy link
Author

Choose a reason for hiding this comment

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

i did, thank you


const decodedKey = decodeURIComponent((key || "").replace(/\+/g, " "));
const decodedValue = decodeURIComponent((value || "").replace(/\+/g, " "));

queryParams[decodedKey] = decodedValue;
}
return queryParams;
}

Expand Down
32 changes: 30 additions & 2 deletions Sprint-2/implement/querystring.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,36 @@

const parseQueryString = require("./querystring.js")

test("parses querystring values containing =", () => {
expect(parseQueryString("equation=x=y+1")).toEqual({
test("parses querystring values containing +", () => {
expect(parseQueryString("equation=x%3Dy%2B1")).toEqual({
"equation": "x=y+1",
});
});
test("returns empty object for empty query string", () => {
expect(parseQueryString("")).toEqual({});
});

test("parses single key with empty value", () => {
expect(parseQueryString("foo=")).toEqual({ foo: "" });
});

test("parses single key with no equals sign", () => {
expect(parseQueryString("foo")).toEqual({ foo: "" });
});

test("parses multiple key-value pairs", () => {
expect(parseQueryString("a=1&b=2")).toEqual({ a: "1", b: "2" });
});

test("decodes URL-encoded characters", () => {
expect(parseQueryString("name=John%20Doe&city=New%20York")).toEqual({
name: "John Doe",
city: "New York",
});
});

test("parses values containing =", () => {
expect(parseQueryString("token=abc=123")).toEqual({
token: "abc=123"
});
});
22 changes: 21 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,23 @@
function tally() {}
function tally(items) {
// Validate input: must be an array
if (!Array.isArray(items)) {
throw new Error("Input must be an array");
}

// Create an object to hold counts
const counts = {};

// Loop through each item and count occurrences
for (const item of items) {
if (counts[item]) {
counts[item] += 1;
} else {
counts[item] = 1;
}
}

return counts;
}

module.exports = tally;

15 changes: 13 additions & 2 deletions Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,23 @@ const tally = require("./tally.js");
// 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 each unique item 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 error on non-array input", () => {
expect(() => tally("not-an-array")).toThrow("Input must be an array");
});
11 changes: 10 additions & 1 deletion Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,29 @@ function invert(obj) {
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?
//This is a built-in JavaScript method that takes an object and returns an array of key-value pairs as arrays.

// d) Explain why the current return value is different from the target output
// it is different because current code is not doing what we was expecting.

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

module.exports = invert;
7 changes: 7 additions & 0 deletions Sprint-2/interpret/invert.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const invert = require("./invert.js");

test("inverts a simple object with unique values", () => {
const input = { a: 1, b: 2 };
const expectedOutput = { 1: "a", 2: "b" };
expect(invert(input)).toEqual(expectedOutput);
});
Loading