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
6 changes: 5 additions & 1 deletion Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
// Predict and explain first...
/* address[0] does not access the houseNumber property of the address object. In JavaScript, objects are
accessed using their property names, not numerical indices. Therefore, address[0] is undefined because
there is no property with the key '0' in the address object. To access the houseNumber property, we should
use address.houseNumber or address['houseNumber']. */

// This code should log out the houseNumber from the address object
// but it isn't working...
Expand All @@ -12,4 +16,4 @@ const address = {
postcode: "XYZ 123",
};

console.log(`My house number is ${address[0]}`);
console.log(`My house number is ${address.houseNumber}`);
6 changes: 5 additions & 1 deletion Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
// Predict and explain first...
/* In JavaScript, objects are not iterable by default, which means you cannot use a for...of loop directly on an object.
The for...of loop is designed to work with iterable objects like arrays, strings, maps, and sets. Since the 'author' object
is not iterable, attempting to use for...of on it will result in a TypeError. To iterate over the properties of an object,
we can use Object.keys(), Object.values(), or Object.entries().*/

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

for (const value of author) {
for (const value of Object.values(author)) {
console.log(value);
}
11 changes: 9 additions & 2 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
// Predict and explain first...
/* In JavaScript, when you try to log an object directly within a template literal, it doesn't automatically
format the object in a readable way. Instead, it converts the object to a string, which results in "[object Object]".
To properly display the ingredients on new lines, we need to join the array elements into a single string with
newline characters in between.*/

// 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 @@ -11,5 +15,8 @@ const recipe = {
};

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
Ingredients:
${recipe.ingredients.map(ingredients => `-${ingredients}`).join("\n")}`);
// Using map to format each ingredient and join to create a single string with new lines
// between each ingredient.

15 changes: 14 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
function contains() {}
function contains(obj, key) {
/**
* Checks if the given array contains the specified value.
* @param {Array} arr - The array to check.
* @param {*} value - The value to search for.
* @returns {boolean} - Returns true if the value is found, otherwise false.
*/
if (obj === null || typeof obj !== "object" || Array.isArray(obj)) {
return false;
}

return Object.prototype.hasOwnProperty.call(obj, key);
}

module.exports = contains;

15 changes: 14 additions & 1 deletion Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,29 @@ 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")).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);
expect(contains(null, "a")).toBe(false);
expect(contains(undefined, "a")).toBe(false);
});
16 changes: 14 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
function createLookup() {
// implementation here
function createLookup(pairs) {
/**
* Creates a lookup object from an array of [key, value] pairs.
* @param {Array<Array<string>>} pairs - An array of [countryCode, currencyCode] pairs.
* @returns {Object} - A lookup object mapping country codes to currency codes.
*/
if (!Array.isArray(pairs)) {
throw new TypeError("Argument must be an array of pairs");
}

return pairs.reduce((lookup, [country, currency]) => {
lookup[country] = currency;
return lookup;
}, {});
}

module.exports = createLookup;
16 changes: 14 additions & 2 deletions Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
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"],
["JP", "JPY"],
];
const expected = {
US: "USD",
CA: "CAD",
JP: "JPY",
};

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

Create a lookup object of key value pairs from an array of code pairs
Expand Down
14 changes: 11 additions & 3 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
function parseQueryString(queryString) {
const queryParams = {};
if (queryString.length === 0) {
if (!queryString || queryString.length === 0) {
return queryParams;
}

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

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
queryParams[key] = value;
if (!pair) continue; // skip empty entries (e.g. trailing &)
const [key, ...rest] = pair.split("=");
const value = rest.length > 0 ? rest.join("=") : null;

// Decode URI components
const decodedKey = decodeURIComponent(key);
const decodedValue = value === null ? null : decodeURIComponent(value);

queryParams[decodedKey] = decodedValue;
}

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

// Additional test cases to cover more edge cases
// query strings with multiple key-value pairs
test("parses querystring with multiple & and =", () => {
expect(parseQueryString("a=1&b=2&c=3")).toEqual({
"a": "1",
"b": "2",
"c": "3",
});
});

// query strings with empty keys
test("parses querystring with empty value", () => {
expect(parseQueryString("key=")).toEqual({
"key": "",
});
});

// query strings with no value
test("parses querystring with no value", () => {
expect(parseQueryString("flag")).toEqual({
"flag": null,
});
});

// query strings with encoded characters
test("parses querystring with encoded characters", () => {
expect(parseQueryString("name=John%20Doe&city=New%20York")).toEqual({
"name": "John Doe",
"city": "New York",
});
});

// query strings with repeated keys
test("parses querystring with repeated keys", () => {
expect(parseQueryString("key=1&key=2")).toEqual({
"key": "2", // assuming last value wins
});
});

// query strings with trailing &
test("parses querystring with trailing &", () => {
expect(parseQueryString("key1=value1&key2=value2&")).toEqual({
"key1": "value1",
"key2": "value2",
});
});

17 changes: 16 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
function tally() {}
function tally(items) {
if (!Array.isArray(items)) {
throw new Error("Input must be an array");
}

const result = {};

for (const item of items) {
if (result[item]) {
result[item]++;
} else {
result[item] = 1;
}
}

return result;
}
module.exports = tally;
16 changes: 15 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,29 @@ const tally = require("./tally.js");
// When passed an array of items
// Then it should return an object containing the count for each unique item

test("tally counts unique items 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 duplicates correctly", () => {
expect(tally(["apple", "banana", "apple"])).toEqual({ apple: 2, banana: 1 });
});

// Given an invalid input like a string
// When passed to tally
// Then it should throw an error
test("tally throws error for non-array input", () => {
expect(() => tally("not an array")).toThrow("Input must be an array");
});
16 changes: 15 additions & 1 deletion Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,34 @@ 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 }
// a) Current return value: { key: 1 }
// a) Target return value: { 1: "a" }

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

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

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

// d) Explain why the current return value is different from the target output
// d) The current return value is different from the target output because the implementation incorrectly assigns the value to a fixed key 'key'
// in the inverted object, rather than using the actual value from the original object as the key in the inverted object. This results in only the
// last processed value being stored under the same key 'key', overwriting any previous entries.

// e) Fix the implementation of invert (and write tests to prove it's fixed!)
// e) Fixed implementation is provided above. Below are the test cases in a separate file.

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

// Test cases for single key-value pair
test("inverts a single key-value pair", () => {
expect(invert({ a: 1 })).toEqual({ 1: "a" });
});

// Test cases for multiple key-value pairs
test("inverts multiple key-value pairs", () => {
expect(invert({ a: 1, b: 2 })).toEqual({ 1: "a", 2: "b" });
});

// Test cases for string values
test("inverts string values", () => {
expect(invert({ a: "x", b: "y" })).toEqual({ x: "a", y: "b" });
});

// Test cases for mixed value types
test("overwrites keys when values are not unique", () => {
expect(invert({ a: 1, b: 1 })).toEqual({ 1: "b" }); // last one wins
});

// Test cases for empty object
test("inverts an empty object", () => {
expect(invert({})).toEqual({});
});