Skip to content

London | ITP MAY | Jamal Laqdiem | Module Data Groups | Sprint-2 #588

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 11 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: 2 additions & 2 deletions Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Predict and explain first...

// It will throw an error because we access a value associated with key in properties object by using the dot notation
// 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 +12,4 @@ const address = {
postcode: "XYZ 123",
};

console.log(`My house number is ${address[0]}`);
console.log(`My house number is ${address.houseNumber}`);
5 changes: 3 additions & 2 deletions Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Predict and explain first...

// it will throw an error because we cannot iterate directly in an object, we need first to make sure that the object become an array to iterate.
// 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 +11,7 @@ const author = {
alive: true,
};

for (const value of author) {
const newObject = Object.values(author)
for (const value of newObject) {
console.log(value);
}
12 changes: 9 additions & 3 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Predict and explain first...

// to log out the title and serves we need to use dot notation to access the property value associated with the key.
// instead to access ingredients values and print them in different lines, we need to loop over recipe.ingredients.
// 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 @@ -8,8 +9,13 @@ const recipe = {
title: "bruschetta",
serves: 2,
ingredients: ["olive oil", "tomatoes", "salt", "pepper"],


};

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
ingredients:`);

for(ingredient of recipe.ingredients) {
console.log(ingredient)
}
23 changes: 22 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,24 @@
function contains() {}
const containObject = {
first_name : 'john',
surname: 'madim',
date_of_birth : 1986,
place_of_birth : 'newYork'
}

function contains(obj,propertyName) {
if ( typeof obj !== 'object'|| obj === null || Array.isArray(obj)){
throw new Error ('Invalid first argument parameter, need to be an object.')
}
if (Object.keys(obj).length ===0){
return false
}

const keyObject = Object.keys(obj)
const hasPropertyName = keyObject.includes(propertyName)
return hasPropertyName

}



module.exports = contains;
39 changes: 35 additions & 4 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,55 @@ as the object doesn't contains a key of 'c'
*/

// Acceptance criteria:

describe('conatains function',() => {
// 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('should return true if the object contains the property', () => {
const testObject = { a: 1, b: 2 };
expect(contains(testObject, 'a')).toBe(true);
expect(contains(testObject, 'b')).toBe(true);
expect(contains({ surname: 'madin', date_of_birth: 1986 }, 'surname')).toBe(true)
});
// Given an empty object
// When passed to contains
// Then it should return false
test.todo("contains on empty object returns false");
test("should return false when passed an empty object", () => {
expect(contains({}, 'surname')).toBe(false);
expect(contains({}, 'anyProperty')).toBe(false);
});

// Given an object with properties
// When passed to contains with an existing property name
// Then it should return true

test('should return true if the object contains the property', () => {
const testObject = { a: 1, b: 2 };
expect(contains(testObject, 'a')).toBe(true);
expect(contains(testObject, 'b')).toBe(true);
expect(contains({ first_name: 'john', date_of_birth: 1986 }, 'first_name')).toBe(true)
});
// Given an object with properties
// When passed to contains with a non-existent property name
// Then it should return false

test('should return false if the object does not contain the property', () => {
const testObject = { a: 1, b: 2 };
expect(contains(testObject, 'c')).toBe(false);
expect(contains(testObject, 'x')).toBe(false);
expect(contains({ surname: 'madin', date_of_birth: 1986 }, 'place_of_birth')).toBe(false);
});
// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error

test('should throw an error for invalid parameters like an array', () => {
expect(() => contains([], 'surname')).toThrow('Invalid parameter: The first argument must be a non-null, non-array object.')

expect(() => contains(null, 'first_name')).toThrow('Invalid parameter: The first argument must be a non-null, non-array object.')
expect(() => contains(123, 'first_name')).toThrow('Invalid parameter: The first argument must be a non-null, non-array object.');

// Test with undefined
expect(() => contains(undefined, 'surname')).toThrow('Invalid parameter: The first argument must be a non-null, non-array object.');
})

});
13 changes: 11 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
function createLookup() {
// implementation here
const countryCurrency = [["MAR","MAD"],["UK","GBP"],["US","USD"]]


function createLookup(dataCurrency) {

return dataCurrency.reduce((acc,entry) => {
const [countryCode,currencyCode]=entry
acc[countryCode]= currencyCode
return acc
},{})
}

console.log(createLookup(countryCurrency))
module.exports = createLookup;
28 changes: 27 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");

describe('createLookup function', () => {

test("creates a country currency code lookup for multiple codes", () =>{
const dataCurrency = [['MAR','MAD'],['US', 'USD'], ['CA', 'CAD']];
const result = createLookup(dataCurrency);
expect(result).toEqual({
'MAR': 'MAD',
'US': 'USD',
'CA': 'CAD'
});
});

});

/*

Expand Down Expand Up @@ -33,3 +46,16 @@ It should return:
'CA': 'CAD'
}
*/
test("handles an empty array input", () => {
const emptyArray = [];
const result = createLookup(emptyArray);
expect(result).toEqual({});
});

test("handles a single country currency pair", () => {
const singlePair = [['JP', 'JPY']];
const result = createLookup(singlePair);
expect(result).toEqual({
'JP': 'JPY'
});
});
8 changes: 5 additions & 3 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ function parseQueryString(queryString) {
const keyValuePairs = queryString.split("&");

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

return queryParams;
}

module.exports = parseQueryString;
console.log(parseQueryString("equation=x=y+1"))
console.log(parseQueryString(""))
console.log(parseQueryString("a=1&&b=2"))
module.exports = parseQueryString;
32 changes: 32 additions & 0 deletions Sprint-2/implement/querystring.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,40 @@

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

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

test("returns an empty object for an empty query string", () => {
expect(parseQueryString("")).toEqual({});
});

test("handles keys with no assigned value", () => {
expect(parseQueryString("key_no_value")).toEqual({
"key_no_value": undefined
});
});

test("handles keys with an empty string value (e.g., 'key=')", () => {
expect(parseQueryString("key_empty_value=")).toEqual({
"key_empty_value": ""
});
});

test("handles multiple '&' by returning correct object and no empty keys", () => {
expect(parseQueryString("a=1&&b=2")).toEqual({
"a": "1",
"b": "2"
});
expect(Object.keys(result)).not.toContain("")
});

test("parses querystring values containing '='", () => {
expect(parseQueryString("equation=x=y+1")).toEqual({
"equation": "x=y+1",
});
});
});
17 changes: 16 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
function tally() {}
function tally(arr) {
objectResult = {}
if(arr.length ===0)
return {}
if( !Array.isArray(arr)) {
throw new Error ('Error parameter must be an array.')
}
for(count of arr) {
objectResult[count]= (objectResult[count] || 0) +1 ;

Choose a reason for hiding this comment

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

Very clever solution - well done

Copy link
Author

Choose a reason for hiding this comment

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

thanks for reviewing.

}

return objectResult
}

console.log(tally(['a','b','c','c']))
console.log(tally([]))
console.log(tally("Hello"))
module.exports = tally;
18 changes: 15 additions & 3 deletions Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,34 @@ const tally = require("./tally.js");
* tally(['a', 'a', 'a']), target output: { a: 3 }
* tally(['a', 'a', 'b', 'c']), target output: { a : 2, b: 1, c: 1 }
*/
describe('tally function tests', () => {

// Acceptance criteria:

// 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('When passed an array of item, then it should return an object containing the count for each unique item',() =>{
expect(tally(['a','o,','h'])).toEqual({a:1, o:1,h: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(' Given an array with duplicate item, should return counts for each unique item',() =>{
expect(tally(['a','o,','o'])).toEqual({a:1, o:2})
})
// Given an invalid input like a string
// When passed to tally
// Then it should throw an error
test(' Given an invalid input like a string, should throw an error',() =>{
expect(() => tally('Hello World')).toThrow('Error: Parameter must be an array.')

})
})
40 changes: 33 additions & 7 deletions Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,50 @@

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


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

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

return invertedObj;

}
console.log(invert({a:1})) // output {1:a}
console.log(invert({ a: 1, b: 2 })) // output {1:a,2:b}
console.log(invert({})) //output {{}}
console.log(invert({name:'Mike',age:33})) // output {Mike:'name', 33:age}

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

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

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

// The target return value should be {1:a,2:b}
// c) What does Object.entries return? Why is it needed in this program?

// Object.entries return the keys and values of the object(obj)
// d) Explain why the current return value is different from the target output

// The difference happen when using the dot notation to access literal string instead of expression, it does not use the value of key variable.
// e) Fix the implementation of invert (and write tests to prove it's fixed!)

//test 1:
const result1 = invert({a:1});
const expected1 = {1:'a'};
console.log(`Test 1: Input {a:1}, Expected ${JSON.stringify(expected1)}, Actual ${JSON.stringify(result1)}`);

Choose a reason for hiding this comment

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

Why did you use JSON.stringify() here? What does it do and what benefit does it provide?

Copy link
Author

Choose a reason for hiding this comment

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

Thanks for reviewing, I used JSON.stringify() for readability and consistency, which it make it easy to read, compare and copy-paste.

console.log(`Result: ${JSON.stringify(result1) === JSON.stringify(expected1) ? 'PASS' : 'FAIL'}`);
//test 2:
const result2 = invert({ a: 1, b: 2 });
const expected2 = {1:'a', 2:'b'};
console.log(`Test 2: Input {a:1, b:2}, Expected ${JSON.stringify(expected2)}, Actual ${JSON.stringify(result2)}`);
console.log(`Result: ${JSON.stringify(result2) === JSON.stringify(expected2) ? 'PASS' : 'FAIL'}`);
//test 3:
const result3 = invert({});
const expected3 = {};
console.log(`Test 3: Input {}, Expected ${JSON.stringify(expected3)}, Actual ${JSON.stringify(result3)}`);
console.log(`Result: ${JSON.stringify(result3) === JSON.stringify(expected3) ? 'PASS' : 'FAIL'}`);
//test 4:
const result4 = invert({name:'Mike',age:33});
const expected4 = {Mike:'name',33:'age'};
console.log(`Test 4: Input {name:'Mike',age:33}, Expected ${JSON.stringify(expected4)}, Actual ${JSON.stringify(result4)}`);
console.log(`Result: ${JSON.stringify(result4) === JSON.stringify(expected4) ? 'PASS' : 'FAIL'}`);
1 change: 1 addition & 0 deletions Sprint-2/interpret/tempCodeRunnerFile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log(`Test 1: Input {a:1}, Expected ${JSON.stringify(expected1)}, Actual ${JSON.stringify(result1)}`);