Skip to content

ITP -Northwest- JAN 2025 | Jan Lo | Module-Data groups | SPRINT 2 | WEEK 7 #506

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 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
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}`);
2 changes: 1 addition & 1 deletion Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ 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")}`);
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() {}
function contains(element, key) {
const result = element[key];

// console.log({
// key,
// typeKey: typeof key,

// result,
// typeResult: typeof result
// })

// if undefined
// return false as doesnt exist
// else, does exist!
// return true

if (result === undefined) return false;
else return true;

}
Copy link
Contributor

Choose a reason for hiding this comment

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

This approach is not bulletproof because a property can be assigned an undefined value. For example,

  let obj { x: undefined };  // An object with a property named "x", and its value is undefined.

Can you figure out how else to improve the code?

console.log(contains({a: 1, b: 2}, 'a'))
console.log(contains({a: 1, b: 2}, 'c'))
console.log(contains({firstName: "Cam" }, 'firstName'))
module.exports = contains;
18 changes: 14 additions & 4 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const contains = require("./contains.js");
Implement a function called contains that checks an object contains a
particular property

E.g. contains({a: 1, b: 2}, 'a') // returns true
E.g. contains({a: 1, b: 2}, 'a') // returns true
as the object contains a key of 'a'

E.g. contains({a: 1, b: 2}, 'c') // returns false
Expand All @@ -20,16 +20,26 @@ 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", () => {
expect(contains({})).toBe (false);
});
// Given an object with properties
// When passed to contains with an existing property name
// Then it should return true
test("contains with an existing property name", () => {
expect(contains({a: 1, b: 2}, 'a')).toBe (true);
});

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

test("contains with a non-existent property name", () => {
expect(contains({a: 1, b: 2}, 'c')).toBe (false);
});
// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error
test("invalid parameters", () => {
expect(contains(["apple", "orange", "pear"])).toBe (false);
});

Comment on lines +42 to +45
Copy link
Contributor

Choose a reason for hiding this comment

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

Invalid parameters could also be other types of values. For examples, null, "some string", 123, undefined.

With your current implementation, contains(["apple", "orange", "pear"], "0") and contains("ABC", "0") would return true`.

You would need to add code to your function to check the first parameter is a valid object and is not an array.

Note: array is a kind of objects in JS.

53 changes: 51 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,54 @@
function createLookup() {
// implementation here
// function createLookup(countryCurrencyPairs) {
// for( let i = 0; i < countryCurrencyPairs.length; i++) {
// const countryCurrencyPair = countryCurrencyPairs[i]

// // console.log({
// // countryCurrencyPairs,
// // i,
// // value: countryCurrencyPairs[i],
// // countryCurrencyPair,

// // })

// //console.log('i am here:', countryCurrencyPairs[[i]])
// console.log(countryCurrencyPair[])

// }

// return countryCurrencyPairs;

// const country = countryCurrencyPair[0]
// const currency = countryCurrencyPair[1]

// return{[country]:currency};


// // implementation here
// }

// function createSingleLookup(countryCurrencyPair) {
// const country = countryCurrencyPair[0]
// const currency = countryCurrencyPair[1]

// return{[country]:currency};
// }

// console.log(createLookup([['US', 'USD'], ['CA', 'CAD']]))

// console.log(createSingleLookup(['US', 'USD'])) // return { 'US': 'USD' }

function createLookup(countryCurrencyPairs) {
return countryCurrencyPairs.reduce((lookup, pair) => {
const [country, currency] = pair;
lookup[country] = currency;
return lookup;
}, {});
}

module.exports = createLookup;


// for (let i = 0; i < onlyNumbers.length; i++) {
// total += onlyNumbers[i];
// }
// return total;
6 changes: 5 additions & 1 deletion Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
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 input = [['US', 'USD'], ['CA', 'CAD']];
const expectedOutput = { US: 'USD', CA: 'CAD' };
expect(createLookup(input)).toEqual(expectedOutput);
});

/*

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

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
const [key, ...valueParts] = pair.split("=");
const value = valueParts.join("=");
queryParams[key] = value;
Copy link
Contributor

Choose a reason for hiding this comment

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

Your approach works.

Please note that in real querystring, both key and value are percent-encoded or URL encoded in the URL. For example, the string "5%" will be encoded as "5%25". So to get the actual value of "5%25" (whether it is a key or value in the querystring), you should call a function to decode it.
May I suggest looking up any of these terms, and "How to decode URL encoded string in JS"?

}

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

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

test("parses query strings with multiple key-value pairs", () => {
expect(parseQueryString("key1=value1&key2=value2")).toEqual({
"key1": "value1",
"key2": "value2",
});
});
15 changes: 12 additions & 3 deletions Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
function tally() {}

module.exports = tally;
function tally(items) {
if (!Array.isArray(items)) {
throw new Error("Input must be an array");
}

return items.reduce((counts, item) => {
counts[item] = (counts[item] || 0) + 1;
return counts;
}, {});
}

module.exports = tally;
16 changes: 15 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,26 @@ 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 on an array with duplicate items", () => {
expect(tally(['a', 'a', 'b', 'c', 'a', 'b'])).toEqual({
a: 3,
b: 2,
c: 1,
});
});

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

test("tally throws an error for invalid input (string)", () => {
expect(() => tally("not an array")).toThrow("Input must be an array");
});
15 changes: 14 additions & 1 deletion Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,33 @@ function invert(obj) {
const invertedObj = {};

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

return invertedObj;
}

module.exports = invert;

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

//Current return value: { key: 1 }

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

//Current return value: { key: 2 }

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

//Target return value: { "1": "a", "2": "b" }.

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

// Object.entries returns an array of [key, value] pairs from the object.

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

// The current implementation incorrectly assigns the value to a property literally
// named "key" instead of dynamically using the value as the key.

// e) Fix the implementation of invert (and write tests to prove it's fixed!)
17 changes: 17 additions & 0 deletions Sprint-2/interpret/invert.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const invert = require("./invert.js");

test("inverts an object with one key-value pair", () => {
expect(invert({ a: 1 })).toEqual({ "1": "a" });
});

test("inverts an object with multiple key-value pairs", () => {
expect(invert({ a: 1, b: 2 })).toEqual({ "1": "a", "2": "b" });
});

test("handles an empty object", () => {
expect(invert({})).toEqual({});
});

test("handles objects with numeric keys and string values", () => {
expect(invert({ 1: "a", 2: "b" })).toEqual({ a: "1", b: "2" });
});