Skip to content

Sheffield | May-2025 | Hassan Osman | Sprint 2 Coursework #577

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 18 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
4 changes: 3 additions & 1 deletion Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
// Predict and explain first...
// prediction before running code: This leads to an error as this isn't an array where values accessed via index/position. values should be accessed via keys/properties in objects.
//observations after running code: logged out "undefined" for ${address[0]}` as this expression can't be matched with any property inside the object

// 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}`);
7 changes: 5 additions & 2 deletions Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
// Predict and explain first...
// prediction before running code: because accessing values of objects should've been done via dot notation or the square brackets method.
//observations after running code: the "for.. of" method only works on iterable objects excluding "plain objects". "For...in" method could be used instead.

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

for (const value of author) {
console.log(value);
for (const value in author) {
console.log(author[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,6 @@
// Predict and explain first...
// prediction before running code: this template literal expression: "${recipe}" won't give the expected results for the "ingredients" part.
// observations after running code: ${recipe}` evaluates to [object Object]. This is because template literal ALONE converts an object into a string with unreadable properties.

// 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 +12,4 @@ 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:\n${recipe.ingredients.join("\n")}`);
10 changes: 9 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
function contains() {}
function contains(object, property) {
if (typeof object !== "object" || object == null || Array.isArray(object)) {
return false;
}

return object.hasOwnProperty(property);
}



module.exports = contains;
48 changes: 47 additions & 1 deletion Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,62 @@ 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", () => {

const currentOutput = contains({}, "2");
const targetOutput = false;
expect(currentOutput).toEqual(targetOutput);
});

// Given an object with properties
// When passed to contains with an existing property name
// Then it should return true
const user = {
id: 101,
name: "Amina Yusuf",
email: "amina@example.com",
isVerified: true,
};
test("an object contains an existing property name returns true", () => {
const currentOutput = contains(user, "name");
const targetOutput = true;
expect(currentOutput).toEqual(targetOutput);
});

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

const book = {
title: "Harry Potter and the Sorcerer's Stone",
author: "J.K. Rowling",
publishedYear: 1997,
genres: "Fantasy",
pages: 309
};

test("an object doesn't contain a property name returns false", () => {
const currentOutput = contains(book, "series");
const targetOutput = false;
expect(currentOutput).toEqual(targetOutput);
});

// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error

const programmingLanguages = ["JavaScript", "Python", "Java", "C++", "Go", "Rust", "Ruby"];
const languages = null;
const name = "Hassan";

test("Returns false when invalid parameters are passed", () => {
const currentOutput = contains(programmingLanguages, "3");
const targetOutput = false;
expect(currentOutput).toEqual(targetOutput);
const currentOutput1 = contains(languages, "null");
const targetOutput1 = false;
expect(currentOutput1).toEqual(targetOutput1);
const currentOutput2 = contains(name, "Hassan");
const targetOutput2 = false;
expect(currentOutput2).toEqual(targetOutput2);
});
5 changes: 3 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
function createLookup() {
// implementation here
function createLookup(array) {
return Object.fromEntries(array);

}

module.exports = createLookup;
15 changes: 14 additions & 1 deletion Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
const createLookup = require("./lookup.js");

test.todo("creates a country currency code lookup for multiple codes");
const countryCurrencyPairs = [["US", "USD"], ["GB", "GBP"], ["JP", "JPY"], ["NG", "NGN"], ["IN", "INR"], ["CA", "CAD"]];

test("creates a country currency code lookup for multiple codes", () => {
const currentOutput = createLookup(countryCurrencyPairs);
const targetOutput = {
US: "USD",
GB: "GBP",
JP: "JPY",
NG: "NGN",
IN: "INR",
CA: "CAD"
};
expect(currentOutput).toEqual(targetOutput);
});

/*

Expand Down
16 changes: 13 additions & 3 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,24 @@ function parseQueryString(queryString) {
if (queryString.length === 0) {
return queryParams;
}

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

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

if (separatorIndex === -1) {
queryParams[pair] = "";
} else {
const key = decodeURIComponent(pair.slice(0, separatorIndex));
const value = decodeURIComponent(pair.slice(separatorIndex + 1));
queryParams[key] = value;
}
}
return queryParams;
}

module.exports = parseQueryString;


console.log(parseQueryString("equation=x=y+1"));
47 changes: 46 additions & 1 deletion Sprint-2/implement/querystring.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,53 @@

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

test("parses querystring values containing multiple '=' signs", () => {
expect(parseQueryString("name=JohnDoe&age=30&country=Canada&sort=recent&showDetails=true")).toEqual({
name: "JohnDoe",
age: "30",
country: "Canada",
sort: "recent",
showDetails: "true"
});
});



test("parses an empty querystring & returns an empty object", () => {
expect(parseQueryString("")).toEqual({});
});




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




test("parses querystring values without '=' & returns keys only", () => {
expect(parseQueryString("fullName")).toEqual({fullName: "" });
});




test("parses querystring with duplicate/repeated keys & returns the last key-value pair", () => {
expect(parseQueryString("haircut=buzzCut&haircut=mullet&haircut=lowFade&shaver=braun&shaver=philips&shaver=wahl")).toEqual({
haircut: "lowFade",
shaver: "wahl",
});
});


test("parses an encoded querystring & returns decoded key-value pairs", () => {
expect(parseQueryString("name=John%20Doe&email=john.doe%40example.com&message=Hello%2C%20how%20are%20you%3F")).toEqual({
name: "John Doe",
email: "john.doe@example.com",
message: "Hello, how are you?"
})
})
10 changes: 9 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
function tally() {}
function tally(list) {
if (!Array.isArray(list)) {
throw new Error("Invalid input!");
}
return list.reduce((rep, element) => {
rep[element] = (rep[element] || 0) + 1;
return rep;
}, {});
}

module.exports = tally;
26 changes: 25 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,36 @@ 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");

const emptyArray = [];

test("tally on an empty array returns an empty object", () => {
const currentOutput = tally(emptyArray);
const targetOutput = {};
expect(currentOutput).toEqual(targetOutput);
});

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

const animals = ['cat', 'dog', 'cat', 'bird', 'dog', 'dog', 'rabbit', 'cat'];

test("tally on an array returns an object with the frequency of each item as properties", () => {
const currentOutput = tally(animals);
const targetOutput = {cat: 3, dog: 3, bird: 1, rabbit: 1};
expect(currentOutput).toEqual(targetOutput);
});

// Given an invalid input like a string
// When passed to tally
// Then it should throw an error

test("tally throws an error when given invalid input", () => {
const name = "Hassan";
const age = null;
const subjectsHobbies = {Math: "puzzles", Science: "experiments", Art: "drawing"};
expect(() => tally(name)).toThrow("Invalid input!");
expect(() => tally(age)).toThrow("Invalid input!");
expect(() => tally(subjectsHobbies)).toThrow("Invalid input!");
});
44 changes: 43 additions & 1 deletion Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,55 @@ function invert(obj) {
}

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

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

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

// c) What does Object.entries return? Why is it needed in this program?
// it returns an array of key-value pairs from an object.
//it's needed in order to loop through each key-value pairs of an object.

// d) Explain why the current return value is different from the target output
// because line 13 is not written accordingly. The current arrangement always starts with keys and then values.
// Most importantly, there's a bug. Currently, it returns "key" as if it's a key/property name. Refer to (a & b)



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


const sports = {
soccer: "ball",
tennis: "racket",
basketball: "hoopBall",
baseball: "bat",
swimming: "goggles",
};

console.log(invert(sports));

// test("when 'invert' passed an object it returns the object with keys & values swapped.", () => {
// expect(invert(sports)).toEqual({
// ball: "soccer",
// racket: "tennis",
// hoopBall: "basketball",
// bat: "baseball",
// goggles: "swimming",
// });
// });