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
10 changes: 9 additions & 1 deletion Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@
// but it isn't working...
// Fix anything that isn't working

// PREDICTION: The code will log "My house number is undefined" because address[0]
// tries to access the element at index 0 like an array, but address is an object.
// Objects don't have numeric indexes — they have named keys like "houseNumber".

// EXPLANATION: address[0] looks for a key literally named "0" on the object,
// which doesn't exist, so it returns undefined.
// The fix is to use address.houseNumber (dot notation) or address["houseNumber"] (bracket notation).

const address = {
houseNumber: 42,
street: "Imaginary Road",
Expand All @@ -12,4 +20,4 @@ const address = {
postcode: "XYZ 123",
};

console.log(`My house number is ${address[0]}`);
console.log(`My house number is ${address.houseNumber}`);
9 changes: 8 additions & 1 deletion Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@
// 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

// PREDICTION: The code will throw a TypeError: author is not iterable.

// EXPLANATION: for...of works on iterables (arrays, strings, Maps, Sets etc.).
// Plain objects are NOT iterable by default, so you cannot use for...of directly
// on an object. To iterate over an object's values, you need Object.values(author)
// which returns an array of the values that for...of can then loop over.

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

for (const value of author) {
for (const value of Object.values(author)) {
console.log(value);
}
10 changes: 9 additions & 1 deletion Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@
// Each ingredient should be logged on a new line
// How can you fix it?

// PREDICTION: The code will log "bruschetta serves 2" then "ingredients:"
// then "[object Object]" — because embedding an object directly in a template
// literal calls .toString() on it, which returns "[object Object]".

// EXPLANATION: recipe is an object, so ${recipe} just gives "[object Object]".
// We need to access the ingredients array specifically and join its items
// with newlines: ${recipe.ingredients.join("\n")} logs each ingredient on its own line.

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

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
${recipe.ingredients.join("\n")}`);
5 changes: 4 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
function contains() {}
function contains(obj, prop) {
if (typeof obj !== "object" || obj === null || Array.isArray(obj)) return false;
return Object.prototype.hasOwnProperty.call(obj, prop);
}

module.exports = contains;
42 changes: 12 additions & 30 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,17 @@
const contains = require("./contains.js");

/*
Implement a function called contains that checks an object contains a
particular property
test("contains on empty object returns false", () => {
expect(contains({}, "a")).toBe(false);
});

E.g. contains({a: 1, b: 2}, 'a') // returns true
as the object contains a key of 'a'
test("returns true when object has the property", () => {
expect(contains({ a: 1, b: 2 }, "a")).toBe(true);
});

E.g. contains({a: 1, b: 2}, 'c') // returns false
as the object doesn't contains a key of 'c'
*/
test("returns false when object does not have the property", () => {
expect(contains({ a: 1, b: 2 }, "c")).toBe(false);
});

// Acceptance criteria:

// 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

// Given an empty object
// When passed to contains
// Then it should return false
test.todo("contains on empty object returns false");

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

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

// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error
test("returns false for array input", () => {
expect(contains([1, 2, 3], "0")).toBe(false);
});
4 changes: 2 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
function createLookup() {
// implementation here
function createLookup(pairs) {
return Object.fromEntries(pairs);
}

module.exports = createLookup;
40 changes: 9 additions & 31 deletions Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,35 +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" });
});

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

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']]

When
- createLookup function is called with the country-currency array as an argument

Then
- It should return an object where:
- The keys are the country codes
- The values are the corresponding currency codes

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

When
createLookup(countryCurrencyPairs) is called

Then
It should return:
{
'US': 'USD',
'CA': 'CAD'
}
*/
test("creates lookup for a single pair", () => {
expect(createLookup([["GB", "GBP"]])).toEqual({ GB: "GBP" });
});
25 changes: 19 additions & 6 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
function parseQueryString(queryString) {
const queryParams = {};
if (queryString.length === 0) {
return queryParams;
}
const keyValuePairs = queryString.split("&");
if (queryString.length === 0) return queryParams;

const keyValuePairs = queryString.split("&").filter(pair => pair.length > 0);

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
queryParams[key] = value;
const eqIndex = pair.indexOf("=");
const rawKey = eqIndex === -1 ? pair : pair.slice(0, eqIndex);
const rawValue = eqIndex === -1 ? "" : pair.slice(eqIndex + 1);

const key = decodeURIComponent(rawKey.replace(/\+/g, " "));
const value = decodeURIComponent(rawValue.replace(/\+/g, " "));

if (Object.prototype.hasOwnProperty.call(queryParams, key)) {
if (Array.isArray(queryParams[key])) {
queryParams[key].push(value);
} else {
queryParams[key] = [queryParams[key], value];
}
} else {
queryParams[key] = value;
}
}

return queryParams;
Expand Down
8 changes: 7 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
function tally() {}
function tally(arr) {
if (!Array.isArray(arr)) throw new Error("Input must be an array");
return arr.reduce((acc, item) => {
acc[item] = (acc[item] || 0) + 1;
return acc;
}, {});
}

module.exports = tally;
43 changes: 15 additions & 28 deletions Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,21 @@
const tally = require("./tally.js");

/**
* tally array
*
* In this task, you'll need to implement a function called tally
* that will take a list of items and count the frequency of each item
* in an array
*
* For example:
*
* tally(['a']), target output: { a: 1 }
* tally(['a', 'a', 'a']), target output: { a: 3 }
* tally(['a', 'a', 'b', 'c']), target output: { a : 2, b: 1, c: 1 }
*/
test("tally on an empty array returns an empty object", () => {
expect(tally([])).toEqual({});
});

// Acceptance criteria:
test("tally counts a single item", () => {
expect(tally(["a"])).toEqual({ a: 1 });
});

// 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 duplicate items", () => {
expect(tally(["a", "a", "a"])).toEqual({ a: 3 });
});

// 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 counts multiple unique items", () => {
expect(tally(["a", "a", "b", "c"])).toEqual({ a: 2, b: 1, c: 1 });
});

// Given an array with duplicate items
// When passed to tally
// Then it should return counts for each unique item

// Given an invalid input like a string
// When passed to tally
// Then it should throw an error
test("throws an error for invalid input like a string", () => {
expect(() => tally("invalid")).toThrow();
});
28 changes: 27 additions & 1 deletion Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,46 @@ function invert(obj) {
const invertedObj = {};

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

return invertedObj;
}

// a) What is the current return value when invert is called with { a : 1 }
// ANSWER: The ORIGINAL (broken) code had invertedObj.key = value, which always sets
// a literal property named "key" rather than using the variable. So calling
// invert({ a: 1 }) would return { key: 1 } — the key name is the string "key",
// not "1" as intended.

// b) What is the current return value when invert is called with { a: 1, b: 2 }
// ANSWER: With the original broken code, each iteration overwrites the same "key"
// property, so the result would be { key: 2 } — only the last value survives
// because every iteration does invertedObj.key = value (literal property "key").

// c) What is the target return value when invert is called with {a : 1, b: 2}
// ANSWER: { "1": "a", "2": "b" }
// The keys and values are swapped: original keys become values, original values
// become keys. Object keys are always strings, so the numbers 1 and 2 become "1" and "2".

// c) What does Object.entries return? Why is it needed in this program?
// ANSWER: Object.entries(obj) returns an array of [key, value] pairs for every
// property in the object. For example, Object.entries({ a: 1, b: 2 }) returns
// [["a", 1], ["b", 2]]. It is needed here because for...of cannot loop over a
// plain object directly \u2014 it only works on iterables like arrays. Object.entries
// converts the object into an iterable array of pairs so we can destructure each
// [key, value] and swap them.

// d) Explain why the current return value is different from the target output
// ANSWER: The original code used invertedObj.key = value (dot notation with the
// literal word "key") instead of invertedObj[value] = key (bracket notation using
// the variable). Dot notation always creates a property with the exact name you
// type \u2014 "key" \u2014 rather than using the variable's value as the property name.
// Bracket notation evaluates the expression inside the brackets, so invertedObj[value]
// correctly uses whatever value holds (e.g. 1, 2) as the new key name.

// e) Fix the implementation of invert (and write tests to prove it's fixed!)
// ANSWER: Fixed above \u2014 changed invertedObj.key = value to invertedObj[value] = key
// Tests are in a separate invert.test.js file.

module.exports = invert;
Loading
Loading