Skip to content

Glasgow | ITP MAY | MIRABELLE MORAH | Module Data Groups | Sprint-2 #587

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
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,5 +1,7 @@
// Predict and explain first...

// It returns back "My house number is undefined" because it's accessing properties using an index instead of the property name.

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

console.log(`My house number is ${address[0]}`);
//added dot notation to access houseNumber

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

// no proper use of for loop

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

// error in line 16 and throws the error "TypeError: author is not iterable at Object." So this does not work on objects.


const author = {
firstName: "Zadie",
lastName: "Smith",
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);
}
5 changes: 3 additions & 2 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@
// Each ingredient should be logged on a new line
// How can you fix it?

// no access to recipe object properties causes problems. Hence we need to use the correct syntax to access the properties.

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

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
ingredients: ${recipe.ingredients.join("\n")}`);
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, property) {
if (
obj === null ||
typeof obj !== "object" ||
Array.isArray(obj)
) {
return false;
}
return Object.prototype.hasOwnProperty.call(obj, property);
}

module.exports = contains;
52 changes: 36 additions & 16 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,39 @@ as the object doesn't contains a key of 'c'
// 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
describe("contains function", () => {

// Given an empty object
// When passed to contains
// Then it should return false

test("contains on empty object returns false", () => {
expect(contains({}, "any")).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 for existing property", () => {
expect(contains({a: 1, b: 2}, "a")).toBe(true);
expect(contains({x: 10, y: 20}, "y")).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-existent property", () => {
expect(contains({a: 1, b: 2}, "c")).toBe(false);
expect(contains({x: 10, y: 20}, "z")).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 for arrays or non-object", () => {
expect(contains([], "length")).toBe(false);
expect(contains(null, "a")).toBe(false);
expect(contains(undefined, "a")).toBe(false);
expect(contains(42, "a")).toBe(false);
});
});

Choose a reason for hiding this comment

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

Good tests

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(codePairs) {

const lookup = {}; // Initialize an empty object to store the lookup pairs

// Iterate over each pair in the input array
for (const pair of codePairs) {
// Ensure the pair has at least two elements (key and value)
if (pair && pair.length >= 2) {
const key = pair[0]; // The first element is the key (e.g., 'US')
const value = pair[1]; // The second element is the value (e.g., 'USD')
lookup[key] = value; // Assign the value to the key in the lookup object
}
}
return lookup;
}

module.exports = createLookup;
40 changes: 39 additions & 1 deletion Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,44 @@
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 countryCurrencyPairs = [
["US", "USD"],
["CA", "CAD"],
["GB", "GBP"],
["JP", "JPY"],
];

const expectedLookup = {
US: "USD",
CA: "CAD",
GB: "GBP",
JP: "JPY",
};

const result = createLookup(countryCurrencyPairs);

expect(result).toEqual(expectedLookup);
});

test("handles an empty array", () => {
const countryCurrencyPairs = [];
const expectedLookup = {};
const result = createLookup(countryCurrencyPairs);
expect(result).toEqual(expectedLookup);
});

test("handles pairs with missing values (should still set key with undefined/null)", () => {
const countryCurrencyPairs = [
["DE", "EUR"],
["XX"], // Missing currency code
];
const expectedLookup = {
DE: "EUR",
XX: undefined,
};
const result = createLookup(countryCurrencyPairs);
expect(result).toEqual(expectedLookup);
});

/*

Expand Down
13 changes: 6 additions & 7 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
function parseQueryString(queryString) {
const queryParams = {};
if (queryString.length === 0) {
return queryParams;
}
const keyValuePairs = queryString.split("&");
if (!queryString) return queryParams;

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
queryParams[key] = value;
for (const pair of queryString.split("&")) {
if (!pair) continue;
const [key, ...rest] = pair.split("=");
const value = rest.length > 0 ? rest.join("=") : "";
queryParams[decodeURIComponent(key)] = decodeURIComponent(value);
}

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

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

test("parses keys with empty values", () => {
expect(parseQueryString("a=&b=2")).toEqual({ a: "", b: "2" });
});

test("parses keys with no value", () => {
expect(parseQueryString("a&b=2")).toEqual({ a: "", b: "2" });
});

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

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

Choose a reason for hiding this comment

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

Good test cases

});
11 changes: 10 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
function tally() {}
function tally(list) {
if (!Array.isArray(list)) {
throw new Error("Input must be an array");
}
const counts = {};
for (const item of list) {
counts[item] = (counts[item] || 0) + 1;
}

Choose a reason for hiding this comment

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

This is a clever and quick way of initialising the object

return counts;
}

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 @@ -23,12 +23,24 @@ 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 returns counts for each unique item", () => {
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 on invalid input", () => {
expect(() => tally("not an array")).toThrow("Input must be an array");
expect(() => tally(123)).toThrow("Input must be an array");
expect(() => tally({})).toThrow("Input must be an array");
});
32 changes: 31 additions & 1 deletion Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}

/*
function invert(obj) {
const invertedObj = {};

Expand All @@ -16,14 +17,43 @@ function invert(obj) {
return invertedObj;
}

console.log(invert({ a: 1, b: 2 }));

*/

// a) What is the current return value when invert is called with { a : 1 }

// ... currently gives { key: 1 }

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

// ... currently gives { key: 2 }

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

// ... should be { "1": "a", "2": "b" }

// c) What does Object.entries return? Why is it needed in this program?

// d) Explain why the current return value is different from the target output
// ... Object.entries returns an array of key-value pairs from the object, which allows us to iterate over them easily.

// d) Explain why the current return value is different from the target output

// ... The current implementation incorrectly assigns the value to the key property of invertedObj instead of using the value as a key in invertedObj. fixed by using invertedObj[value] = key;

Choose a reason for hiding this comment

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

Good explanations

Copy link
Author

Choose a reason for hiding this comment

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

I'm grateful and thank you


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

function invert(obj) {
const invertedObj = {};

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

return invertedObj;
}

console.log(invert({ a: 1 }));
console.log(invert({ a: 1, b: 2 }));

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

test("invert swaps keys and values for single pair", () => {
expect(invert({ a: 1 })).toEqual({ "1": "a" });
});

test("invert swaps keys and values for multiple pairs", () => {
expect(invert({ a: 1, b: 2 })).toEqual({ "1": "a", "2": "b" });
expect(invert({ x: 10, y: 20 })).toEqual({ "10": "x", "20": "y" });
});

test("invert works with string values", () => {
expect(invert({ a: "apple", b: "banana" })).toEqual({ apple: "a", banana: "b" });
});

test("invert returns empty object for empty input", () => {
expect(invert({})).toEqual({});
});
Loading