Skip to content

WM | Abdullah Saleh | Module-Data-Groups | Sprint2 #632

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 25 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
808cd40
Declare array variables.
3bdullah-saleh Jun 28, 2025
a77628d
Iteration throw a function
3bdullah-saleh Jun 28, 2025
365a036
Create a function for finding the mean and add some tests.
3bdullah-saleh Jun 28, 2025
954a7d2
Create a function to sum the values but it is a flawed approach.
3bdullah-saleh Jun 28, 2025
11dc49b
Create a function to find Median of the list
3bdullah-saleh Jun 28, 2025
985755c
Assembling the Median and Mean function.
3bdullah-saleh Jun 28, 2025
3024193
Corrected object key access method for houseNumber
3bdullah-saleh Jul 14, 2025
07e70b4
Access object values using for...of and Object.values()
3bdullah-saleh Jul 14, 2025
9b9fa24
Access ingredients array from recipe object and use .join("\n") to pr…
3bdullah-saleh Jul 14, 2025
c840181
Implement the 'contains' function and write test cases.
3bdullah-saleh Jul 15, 2025
eb0812e
Implemetn 'createLookup' function and create test cases.
3bdullah-saleh Jul 15, 2025
993e7aa
Update the function to handel values containing multiple = and write …
3bdullah-saleh Jul 15, 2025
a5cf549
Implement 'tally' function to count the frequency of each item in an …
3bdullah-saleh Jul 15, 2025
0263db4
Fix invert function and add test case.
3bdullah-saleh Jul 15, 2025
fe6b990
Implement countWords function
3bdullah-saleh Jul 15, 2025
a20b404
Extract coin values with slice, and add test case
3bdullah-saleh Jul 15, 2025
dab6fb5
Refactor calculateMode into two helper functions.
3bdullah-saleh Jul 16, 2025
7cfaa76
Adding the explanation and updating the console.log.
3bdullah-saleh Jul 20, 2025
4fb37a2
Removing the console.log() functions from the code
3bdullah-saleh Jul 20, 2025
06e9628
Removing test.todo from the test file.
3bdullah-saleh Jul 20, 2025
1f20070
Remove console.log function from the code.
3bdullah-saleh Jul 20, 2025
de9c1d4
Handle non-array input in tally and add corresponding test.
3bdullah-saleh Jul 20, 2025
500027d
Adding .filter() to handle empty strings. Also, removed console.log()…
3bdullah-saleh Jul 20, 2025
5198d67
Removed console.log() from the code.
3bdullah-saleh Jul 20, 2025
2cee99e
Remove unnecessary string 0 in slice method for consistency.
3bdullah-saleh Jul 20, 2025
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
2 changes: 1 addition & 1 deletion Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ const address = {
postcode: "XYZ 123",
};

console.log(`My house number is ${address[0]}`);
console.log(`My house number is ${address["houseNumber"]}`);
9 changes: 8 additions & 1 deletion Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

// 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
/*
When I run the code I got this error (TypeError: author is not iterable).
Means that we can not do iteration through the author abject.
That's because plain objects aren't iterable like arrays.
To fix it, we need to convert the object into an iterable structure.
*/

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

for (const value of author) {
for (const value of Object.values(author)) {
console.log(value);
}

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

/*
At he beginning the code will logs the following:
bruschetta serves 2,
ingredients:
olive oil,tomatoes,salt,pepper

To fix this we need to use .join("\n") to join the ingredients by new line.
*/

// 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?
Expand All @@ -10,6 +19,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}, the ingredients required are:
${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(object, keyName) {
if (Object.keys(object) == 0 || !Object.keys(object).includes(keyName) || typeof object !== "object") {
return false
}
else if (Object.keys(object).includes(keyName)) {
return true
}
};



module.exports = contains;
31 changes: 30 additions & 1 deletion Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,45 @@ 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("It will return false when we call contains with an empty object", () => {
const input = {};
const currentOutput = contains(input, "anyKey");
const targetOutput = false;
expect(currentOutput).toStrictEqual(targetOutput);
});

// Given an object with properties
// When passed to contains with an existing property name
// Then it should return true
test("It will return true when we call contains with an existing property name", () => {
const input = {
name: "Ali",
age: 25,
};
const currentOutput = contains(input, "name");
const targetOutput = true;
expect(currentOutput).toStrictEqual(targetOutput);
});

// Given an object with properties
// When passed to contains with a non-existent property name
// Then it should return false
test("It will return false when we call contains with a non-existent property name", () => {
const input = {
name: "Ali",
age: 25,
};
const currentOutput = contains(input, "city");
const targetOutput = false;
expect(currentOutput).toStrictEqual(targetOutput);
});

// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error
test("It will return false when we call contains with an array", () => {
const input = []
const currentOutput = contains(input, "length");
const targetOutput = false;
expect(currentOutput).toStrictEqual(targetOutput);
});
11 changes: 9 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
function createLookup() {
// implementation here
function createLookup(countryCurrencyPairs) {
if (countryCurrencyPairs.length == 0){
return "array is empty"
}
let countryCurrencyObject = {}
for (const array of countryCurrencyPairs){
countryCurrencyObject[array[0]] = array[1];
}
return countryCurrencyObject;
}

module.exports = createLookup;
26 changes: 24 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,27 @@ It should return:
'CA': 'CAD'
}
*/

test("throws error when createLookup is given an empty array", () => {
const input = [];
const currentOutput = createLookup(input);
const targetOutput = "array is empty";
expect(currentOutput).toStrictEqual(targetOutput)

})

test("handel the case when createLookup has only one array inside an array", () => {
const input = [['US', 'USD']];
const currentOutput = createLookup(input);
const targetOutput = {'US': 'USD'};
expect(currentOutput).toStrictEqual(targetOutput)

})

test("handel the case when createLookup has more than one array inside an array", () => {
const input = [['US', 'USD'], ['CA', 'CAD']];
const currentOutput = createLookup(input);
const targetOutput = {'US': 'USD', 'CA': 'CAD'};
expect(currentOutput).toStrictEqual(targetOutput)

})
7 changes: 6 additions & 1 deletion Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ function parseQueryString(queryString) {
const keyValuePairs = queryString.split("&");

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

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

test("handles empty value", () => {
expect(parseQueryString("username=")).toEqual({ username: "" });
});

test("handles empty key", () => {
expect(parseQueryString("=value")).toEqual({ "": "value" });
});

test("handles only ampersands", () => {
expect(parseQueryString("&&&&")).toEqual({});
});

test("handles repeated keys", () => {
expect(parseQueryString("key=value1&key=value2")).toEqual({ key: "value2" });
});

test("handles ampersands at start and end", () => {
expect(parseQueryString("&&name=Ali&&")).toEqual({ name: "Ali" });
});
13 changes: 12 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
function tally() {}
function tally(arrayElements) {
if (typeof arrayElements !== "object") throw new Error("Invalid input");
const tallyObject = {};
for (const item of arrayElements) {
if (tallyObject[item]) {
tallyObject[item] += 1;
} else {
tallyObject[item] = 1;
}
}
return tallyObject;
}

module.exports = tally;
31 changes: 30 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,41 @@ 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", () => {
const input = []
const currentOutput = tally(input)
const targetOutput = {}
expect(currentOutput).toEqual(targetOutput)
});

// Given an array with one item
// When passed to tally
// Then it should return counts of the item, which is 1
test("tally on an array with one item should return counts of the item, which is 1", () => {
const input = ['a']
const currentOutput = tally(input)
const targetOutput = { a : 1}
expect(currentOutput).toEqual(targetOutput)
});


// Given an array with duplicate items
// When passed to tally
// Then it should return counts for each unique item
test("tally on an array with duplicate items should return counts for each unique item", () => {
const input = ['a', 'a', 'a', 'b', 'c', 'd', 'b']
const currentOutput = tally(input)
const targetOutput = { a : 3, b: 2, c: 1, d: 1 }
expect(currentOutput).toEqual(targetOutput)
});

// Given an invalid input like a string
// When passed to tally
// Then it should throw an error
test("tally with an invalid input like a string should throw an error", () => {
try {
tally("")
}catch(err) {
expect(err.message).toBe("Invalid input")
}
});
17 changes: 14 additions & 3 deletions Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,33 @@

function invert(obj) {
const invertedObj = {};
// console.log(Object.entries(obj))

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

return invertedObj;
}
const result = invert({ a: 1, b: 2 });
const expected = { '1': 'a', '2': 'b' };

// a) What is the current return value when invert is called with { a : 1 }
console.assert(JSON.stringify(result) === JSON.stringify(expected), "It should return { '1': 'a', '2': 'b' }")

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

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

// c) What does Object.entries return? Why is it needed in this program?
// Object.entries returns key-value pairs array within array. We needed to separate each key-value pair
// and we could swap them

// d) Explain why the current return value is different from the target output
// Because right now we are not returning the value of the key, we are just adding new key(with the name key)
// to the invertedObj variable. To fix this, we need to use bracket to use the value of the variable key.
// Moreover, we need to swap the object key-value pair.

// e) Fix the implementation of invert (and write tests to prove it's fixed!)
29 changes: 29 additions & 0 deletions Sprint-2/stretch/count-words.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,32 @@

3. Order the results to find out which word is the most common in the input
*/

function countWords(string) {
const punctuation = /[\.,?!]/g; // regular expression to check the following punctuation marks (".", ",", "!", "?")
const stringsIntoArray = string
.replace(punctuation, "")
.toLowerCase()
.split(" ")
.filter(word => word !== ""); // remove the punctuation (e.g. ".", ",", "!", "?") from the string and make the string in lower case then split each word as an element of the array and remove if there are empty strings
const wordObject = {}; // create an empty object {}

for (const word of stringsIntoArray) {
if (wordObject[word]){
wordObject[word] += 1;
}
else {
wordObject[word] = 1;
}
}
// Find the most common word (advanced step)
let mostCommonWord = "";
let maxCount = 0;
for (const [word, count] of Object.entries(wordObject)) {
if (count > maxCount) {
maxCount = count;
mostCommonWord = word;
}
}
return wordObject
}
9 changes: 8 additions & 1 deletion Sprint-2/stretch/mode.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@
// into smaller functions using the stages above

function calculateMode(list) {
const freqs = getFrequencies(list);
return getMostFrequentValue(freqs);
}

function getFrequencies(list) {
// track frequency of each value
let freqs = new Map();

Expand All @@ -19,7 +24,9 @@ function calculateMode(list) {

freqs.set(num, (freqs.get(num) || 0) + 1);
}

return freqs
}
function getMostFrequentValue(freqs) {
// Find the value with the highest frequency
let maxFreq = 0;
let mode;
Expand Down
17 changes: 12 additions & 5 deletions Sprint-2/stretch/till.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,31 @@ function totalTill(till) {
let total = 0;

for (const [coin, quantity] of Object.entries(till)) {
total += coin * quantity;
const x = coin.slice(0, coin.length - 1) * quantity
total += x;
}

return `£${total / 100}`;
}

const till = {
"1p": 10,
"5p": 6,
"50p": 4,
"20p": 10,
"1p": 10,
"5p": 6,
"50p": 4,
"20p": 10,
};
const totalAmount = totalTill(till);

// a) What is the target output when totalTill is called with the till object
// is to return the total amounts in pounds which is in this example qual to £4.4

// b) Why do we need to use Object.entries inside the for...of loop in this function?
// to get each key-value pair alone and assign key to be = coin and value = quantity

// c) What does coin * quantity evaluate to inside the for...of loop?
// multiplication of the key by the value

// d) Write a test for this function to check it works and then fix the implementation of totalTill
const input = totalTill({"1p": 10})
const targetOutput = "£0.1"
console.assert(input === targetOutput, "It should return £0.1")
Loading