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
3 changes: 2 additions & 1 deletion Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Predict and explain first...
// [MM] - The original code returns undefined because it is trying to call houseNumber by index, rather than by key.

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

console.log(`My house number is ${address[0]}`);
console.log(`My house number is ${address.houseNumber}`);
3 changes: 2 additions & 1 deletion Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Predict and explain first...
// [MM] - The original code does not work because it is trying to loop through an array, rather than 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 +12,6 @@ const author = {
alive: true,
};

for (const value of author) {
for (const value of Object.values(author)) {
console.log(value);
}
6 changes: 3 additions & 3 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Predict and explain first...
// [MM] - I expect this programme to log out recipe object rather than the ingredients

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

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
console.log(`${recipe.title} serves ${recipe.serves} ingredients:
${recipe.ingredients.join("\n")}`);
12 changes: 11 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
function contains() {}
function contains(object, value) {
const isNotObject =
typeof object !== "object" || object === null || Array.isArray(object);

if (isNotObject) return false;

return Object.hasOwn(object, value);
}

console.log(contains({ a: 1, b: 2 }, "a"));
console.log(contains(["a", "b"], "a"));

module.exports = contains;
19 changes: 16 additions & 3 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,33 @@ 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("given an object and a property name, returns true if object contains the property, otherwise return false", () => {
expect(contains({ a: 1, b: 2 }, "a")).toBe(true);
expect(contains({ a: 1, b: 2 }, "c")).toBe(false);
});

// Given an empty object
// When passed to contains
// Then it should return false
test.todo("contains on empty object returns false");
test("given an 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("given an object and a property name, returns true if object contains 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("given an object and a property name, returns false if object does not contain 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
test("given an invalid array parameter, returns false", () => {
expect(contains([1, 2, 3], 3)).toBe(false);
});
83 changes: 81 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,84 @@
function createLookup() {
// implementation here
function createLookup(data) {
validateData(data);
return data.reduce((lookup, [country, currency]) => {
lookup[country] = currency;
return lookup;
}, {});
}

// check for valid pairs
const isValidPair = (value) =>
Array.isArray(value) &&
value.length === 2 &&
typeof value[0] === "string" &&
typeof value[1] === "string";

// check for duplicates
const normaliseDataPair = ([country, currency]) => `${country}|${currency}`;
const isDuplicated = (data) =>
new Set(data.map(normaliseDataPair)).size !== data.length;

const validateData = (data) => {
// check that it is an array
if (!Array.isArray(data)) {
throw new Error("Input must be an array");
}
// check that input is not empty
if (data.length === 0) {
throw new Error("Input must not be an empty array");
}

// check that the values are valid
if (data.some((value) => !isValidPair(value))) {
throw new Error("Input must be valid text pairs");
}

// check for duplicates
if (isDuplicated(data)) {
throw new Error("Input must not be duplicated");
}

// check country code has 2 uppercase letters
if (data.some(([country]) => !/^[A-Z]{2}$/.test(country))) {
throw new Error("Country code must be 2 uppercase letters");
}
// check currency code has 3 uppercase letters
if (data.some(([, currency]) => !/^[A-Z]{3}$/.test(currency))) {
throw new Error("Currency code must be 3 uppercase letters");
}
};

// Handle invalid cases
const INVALID_CASES = [
[[], "Input must not be an empty array"],
["hello", "Input must be an array"],
[[1, 2, 3], "Input must be valid text pairs"],
[
[
["US", "USD"],
["US", "USD"],
],
"Input must not be duplicated",
],
];

const printInvalidCases = () => {
for (const [data, expectedMessage] of INVALID_CASES) {
try {
createLookup(data);
console.log(`Unexpected success for ${JSON.stringify(data)}`);
} catch (error) {
console.log("-".repeat(50));
console.log(
`Data: ${JSON.stringify(data)}\nExpected: ${expectedMessage}\nReceived: ${error.message}`
);
}
}
};

if (require.main === module) {
console.log("DATA ERRORS");
printInvalidCases();
console.log("-".repeat(50));
}
module.exports = createLookup;
52 changes: 50 additions & 2 deletions Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
const createLookup = require("./lookup.js");

test.todo("creates a country currency code lookup for multiple codes");

/*

Create a lookup object of key value pairs from an array of code pairs
Expand Down Expand Up @@ -33,3 +31,53 @@ It should return:
'CA': 'CAD'
}
*/

describe("createLookup", () => {
test("maps country codes to currency codes", () => {
expect(
createLookup([
["US", "USD"],
["CA", "CAD"],
])
).toEqual({
US: "USD",
CA: "CAD",
});
});

test.each([
[
"throws when input array is empty",
[],
"Input must not be an empty array",
],
["throws when input is not an array", "hello", "Input must be an array"],
[
"throws when input pairs are invalid",
[1, 2, 3],
"Input must be valid text pairs",
],
[
"throws when duplicate pairs are provided",
[
["US", "USD"],
["US", "USD"],
],
"Input must not be duplicated",
],
])("%s", (_title, data, expecteMessage) => {
expect(() => createLookup(data)).toThrow(expecteMessage);
});

test("throws when country code format is incorrect", () => {
expect(() => createLookup([["us", "USD"]])).toThrow(
"Country code must be 2 uppercase letters"
);
});

test("throws when currency code format is incorrect", () => {
expect(() => createLookup([["US", "usd"]])).toThrow(
"Currency code must be 3 uppercase letters"
);
});
});
18 changes: 15 additions & 3 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,22 @@ function parseQueryString(queryString) {
const keyValuePairs = queryString.split("&");

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
queryParams[key] = value;
}
if (pair === "") continue;

const [keyPart, ...valueParts] = pair.split("=");
const rawKey = keyPart.trim().replace(/\+/g, " ");
const rawValue = valueParts.join("=").trim().replace(/\+/g, " ");
const key = decodeURIComponent(rawKey);
const value = decodeURIComponent(rawValue);

if (queryParams[key] === undefined) {
queryParams[key] = value;
} else if (Array.isArray(queryParams[key])) {
queryParams[key].push(value);
} else {
queryParams[key] = [queryParams[key], value];
}
}
return queryParams;
}

Expand Down
16 changes: 15 additions & 1 deletion Sprint-2/implement/querystring.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// Below are some test cases the implementation doesn't handle well.
// Fix the implementation for these tests, 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("should parse values containing '='", () => {
expect(parseQueryString("equation=a=b-2")).toEqual({
Expand Down Expand Up @@ -46,3 +46,17 @@ test("should store values of a key in an array when the key has 2 or more values
foo: "bar",
});
});

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

test("should ignore leading and trailing ampersands", () => {
expect(parseQueryString("&a=1&b=2&")).toEqual({ a: "1", b: "2" });
});

test("should parse keys and values with plus signs and percent encoding", () => {
expect(parseQueryString("full+name=John+Doe%21")).toEqual({
"full name": "John Doe!",
});
});
34 changes: 33 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,35 @@
function tally() {}
function tally(array) {
if (!Array.isArray(array)) {
throw new Error("Input must be an array");
}

return array.reduce((acc, item) => {
acc[item] = (acc[item] ?? 0) + 1;
return acc;
}, {});
}

// Handle invalid cases
const INVALID_CASES = [["hello", "Input must be an array"]];

const printInvalidCases = () => {
for (const [data, expectedMessage] of INVALID_CASES) {
try {
tally(data);
console.log(`Unexpected success for ${JSON.stringify(data)}`);
} catch (error) {
console.log("-".repeat(50));
console.log(
`Data: ${JSON.stringify(data)}\nExpected: ${expectedMessage}\nReceived: ${error.message}`
);
}
}
};

if (require.main === module) {
console.log("ERROR MESSAGES");
printInvalidCases();
console.log("-".repeat(50));
}

module.exports = tally;
14 changes: 13 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,28 @@ const tally = require("./tally.js");
// 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("return counts for each unique item", () => {
expect(tally(["a", "b", "c"])).toEqual({ a: 1, b: 1, c: 1 });
expect(tally([1, 2, 3])).toEqual({ 1: 1, 2: 1, 3: 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("return counts for each unique item of duplicate items", () => {
expect(tally(["a", "a", "a"])).toEqual({ a: 3 });
});

// Given an invalid input like a string
// When passed to tally
// Then it should throw an error
test("throws when input is not an array", () => {
expect(() => tally("hello")).toThrow("Input must be an array");
});
Loading