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: 4 additions & 2 deletions Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
// Predict and explain first...
// The original code used address[0], which doesn't work because
// address is an object, not an array. Objects have named keys, not numeric indexes.
// So address[0] is undefined.

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

console.log(`My house number is ${address[0]}`);
console.log(`My house number is ${address.houseNumber}`);
12 changes: 7 additions & 5 deletions Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Predict and explain first...

// 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 and explanation:
// The original code uses `for (const value of author)`, but `author` is an object,
// not an array or other iterable. This will throw a TypeError.
// To fix it, we need to loop over the object's values using Object.values().

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

for (const value of author) {
// Fix: use Object.values() to get an array of the values
for (const value of Object.values(author)) {
console.log(value);
}

18 changes: 11 additions & 7 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
// Predict and explain first...

// 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?
// Prediction and explanation:
// The current code tries to log the whole `recipe` object with `${recipe}`,
// but objects are not automatically formatted in a readable way in a template string.
// This will print something like "[object Object]" instead of the ingredients on separate lines.
// To fix it, we need to access the `ingredients` array and log each ingredient individually.

const recipe = {
title: "bruschetta",
serves: 2,
ingredients: ["olive oil", "tomatoes", "salt", "pepper"],
};

// Fix: log title and serves, then loop over ingredients to print each on a new line
console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
ingredients:`);
for (const ingredient of recipe.ingredients) {
console.log(ingredient);
}

11 changes: 10 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
function contains() {}
function contains(obj, prop) {
// Check if the input is a valid object and prop is a string
if (obj === null || typeof obj !== "object" || Array.isArray(obj)) {
return false;
}

// Use Object.hasOwn to check if property exists
return Object.hasOwn(obj, prop);
}

module.exports = contains;

34 changes: 15 additions & 19 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,31 @@
const contains = require("./contains.js");

/*
Implement a function called contains that checks an object contains a
particular property

E.g. contains({a: 1, b: 2}, 'a') // returns true
as the object contains a key of 'a'

E.g. contains({a: 1, b: 2}, 'c') // returns false
as the object doesn't contains a key of 'c'
*/

// 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");
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 returns true when object has the property", () => {
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 returns false when object does not have the property", () => {
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
// Then it should return false
test("contains returns false for invalid input like arrays", () => {
expect(contains([], "a")).toBe(false);
expect(contains(null, "a")).toBe(false);
});

14 changes: 12 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
function createLookup() {
// implementation here
function createLookup(pairs) {
// Validate input: must be an array of arrays
if (!Array.isArray(pairs)) {
return {};
}

const lookup = {};
for (const [country, currency] of pairs) {
lookup[country] = currency;
}
return lookup;
}

module.exports = createLookup;

55 changes: 23 additions & 32 deletions Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,26 @@
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"],
["GB", "GBP"],
];
const result = createLookup(input);

expect(result).toEqual({
US: "USD",
CA: "CAD",
GB: "GBP",
});
});

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

test("returns empty object when given invalid input", () => {
expect(createLookup(null)).toEqual({});
expect(createLookup("not an array")).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'
}
*/
56 changes: 50 additions & 6 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,60 @@
function parseQueryString(queryString) {
const queryParams = {};
if (queryString.length === 0) {
return queryParams;

// Guard: empty or falsy input
if (!queryString) return queryParams;

// Remove leading '?'
if (queryString.startsWith("?")) {
queryString = queryString.slice(1);
if (queryString.length === 0) return queryParams;
}
const keyValuePairs = queryString.split("&");

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
queryParams[key] = value;
const pairs = queryString.split("&").filter((p) => p.length > 0);

const safeDecode = (s) => {
// Replace + with space before decoding
const replaced = s.replace(/\+/g, " ");
try {
return decodeURIComponent(replaced);
} catch (e) {
// If decoding fails, return the replaced string as-is
return replaced;
}
};

for (const pair of pairs) {
const idx = pair.indexOf("=");

let key;
let value;
if (idx === -1) {
// No '=' present: treat as key with empty string value
key = pair;
value = "";
} else {
// Split on first '=' only
key = pair.slice(0, idx);
value = pair.slice(idx + 1);
}

const decodedKey = safeDecode(key);
const decodedValue = safeDecode(value);

if (Object.prototype.hasOwnProperty.call(queryParams, decodedKey)) {
const existing = queryParams[decodedKey];
if (Array.isArray(existing)) {
existing.push(decodedValue);
} else {
queryParams[decodedKey] = [existing, decodedValue];
}
} else {
queryParams[decodedKey] = decodedValue;
}
}

return queryParams;
}

module.exports = parseQueryString;

35 changes: 28 additions & 7 deletions Sprint-2/implement/querystring.test.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,33 @@
// In the prep, we implemented a function to parse query strings.
// Unfortunately, it contains several bugs!
// Below is one test case for an edge case the implementation doesn't handle well.
// Fix the implementation for this test, and try to think of as many other edge cases as possible - write tests and fix those too.

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

test("parses querystring values containing =", () => {
expect(parseQueryString("equation=x=y+1")).toEqual({
"equation": "x=y+1",
equation: "x=y+1",
});
});

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

test("handles empty query string", () => {
expect(parseQueryString("")).toEqual({});
expect(parseQueryString("?")).toEqual({});
});

test("handles keys without value and keys with empty value", () => {
expect(parseQueryString("noValue")).toEqual({ noValue: "" });
expect(parseQueryString("empty=")).toEqual({ empty: "" });
});

test("decodes percent-encoding and plus signs", () => {
expect(parseQueryString("name=John%20Doe&query=hello+world")).toEqual({
name: "John Doe",
query: "hello world",
});
});

test("collects duplicate keys into arrays in order", () => {
expect(parseQueryString("a=1&a=2&a=3")).toEqual({ a: ["1", "2", "3"] });
});

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 = Object.create(null);
for (const item of items) {
if (result[item]) {
result[item] ++;
} else {
result[item] = 1;
}
}
return result;
}

module.exports = tally;

35 changes: 14 additions & 21 deletions Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,27 @@
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 }
*/

// Acceptance criteria:

// Given a function called tally
// When passed an array of items
// Then it should return an object containing the count for each unique item

// 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 items correctly", () => {
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 invalid input like a string
// When passed to tally
// Then it should throw an error
test("tally throws error for invalid input", () => {
expect(() => tally("not an array")).toThrow("Input must be an array");
expect(() => tally(null)).toThrow("Input must be an array");
expect(() => tally(123)).toThrow("Input must be an array");
});

Loading