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 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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);
}

2 changes: 1 addition & 1 deletion Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ const recipe = {

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
${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);
});
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(countryCurrencyPairs) {
if (countryCurrencyPairs.length == 0){
return "array is empty"
}
console.log(countryCurrencyPairs.length)
let countryCurrencyObject = {}
for (const array of countryCurrencyPairs){
countryCurrencyObject[array[0]] = array[1];
}
return countryCurrencyObject;
}

console.log(createLookup([]));

module.exports = createLookup;
24 changes: 24 additions & 0 deletions Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,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)

})
8 changes: 7 additions & 1 deletion Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,17 @@ 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;
}

return queryParams;
}

console.log(parseQueryString("&&name=Ali&&"))
module.exports = parseQueryString;
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" });
});
15 changes: 14 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
function tally() {}
function tally(arrayElements) {
const tallyObject = {}
for (const item of arrayElements) {
if (tallyObject[item]) {
tallyObject[item] += 1;
}
else {
tallyObject[item] = 1;
}
}
return tallyObject;
}

console.log(tally(['a', 'a', 'b', 'a']))
module.exports = tally;

24 changes: 23 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,33 @@ 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', 'a']
const currentOutput = tally(input)
const targetOutput = { a : 2}
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
Expand Down
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(" "); // 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
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;
}
}
console.log("🚀 ~ countWords ~ mostCommonWord:", mostCommonWord)

return wordObject

}
console.log(countWords("You and me and you you!!!!!"), )
10 changes: 9 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 All @@ -32,5 +39,6 @@ function calculateMode(list) {

return maxFreq === 0 ? NaN : mode;
}
console.log(calculateMode([2, 4, 1, 2, 3, 2, 1]))

module.exports = calculateMode;
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;
total += coin.slice("0", coin.length - 1) * quantity;
}

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")
9 changes: 9 additions & 0 deletions prep/array.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// declaring array literal as follows

const items = [4.6, 5.9, 6.99];

// In JavaScript, we can use square bracket notation to access specific elements in the array using an index.

items[0]; // evaluates to 4.6
items[1]; // evaluates to 5.9
items[2]; // evaluates to 6.99
11 changes: 11 additions & 0 deletions prep/assembling.the.parts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const calculateMedian = require('./median');
const calculateMean = require('./mean');

const salaries = [10, 20, 30, 40, 60, 80, 80];
const median = calculateMedian(salaries);

console.log(salaries, "<--- salaries input before we call calculateMean");
const mean = calculateMean(salaries);

console.log(`The median salary is ${median}`);
console.log(`The mean salary is ${mean}`);
Loading