Skip to content
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
5 changes: 4 additions & 1 deletion Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
// Predict and explain first...

//because this not an array we can not use index to access the value
// we need to use the key name instead

// 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 +15,4 @@ const address = {
postcode: "XYZ 123",
};

console.log(`My house number is ${address[0]}`);
console.log(`My house number is ${address["houseNumber"] }`);
4 changes: 2 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...

// for .. of only works with iterable objects like arrays or strings. but author is an object.
// 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,6 @@ const author = {
alive: true,
};

for (const value of author) {
for (const value of Object.values(author)) {//This extracts the values into an array, and arrays ARE iterable, so the loop works.
console.log(value);
}
13 changes: 10 additions & 3 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Predict and explain first...

// if i want to access the ingredients and present each item on a new line i will use \ and the index of each item
// 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 +10,13 @@ const recipe = {
ingredients: ["olive oil", "tomatoes", "salt", "pepper"],
};

//console.log(`${recipe.title} serves ${recipe.serves}
//ingredients:
//${recipe.ingredients[0]}
//${recipe.ingredients[1]}
//${recipe.ingredients[2]}
//${recipe.ingredients[3]}`);
console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
ingredients:
${recipe.ingredients.join("\n")}`);
// this is the shortest way to access each item in the array and present it on a new line
6 changes: 5 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
function contains() {}
function contains(obj, key) {
if (obj === null || typeof obj !== "object") return false;

return Object.prototype.hasOwnProperty.call(obj, key);// Updated to use hasOwnProperty to check for own properties only
}

module.exports = contains;
29 changes: 26 additions & 3 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,43 @@ as the object doesn't contains a key of 'c'
// 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("returns true for an existing property", () => {
const obj = { a: 1, b: 2 };
expect(contains(obj, "a")).toBe(true);
});
// 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({}, "a")).toBe(false);
});

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

test("contains on object with existing property returns true", () => {
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 on object with non-existent property returns false", () => {
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("contains on invalid parameters returns false", () => {
expect(contains("not an object", "a")).toBe(false);
expect(contains(123, "a")).toBe(false);
expect(contains(null, "a")).toBe(false);
expect(contains(undefined, "a")).toBe(false);
});

test("works with arrays using index keys", () => {
const arr = ["a", "b"];
expect(contains(arr, "0")).toBe(true); // own property
expect(contains(arr, "2")).toBe(false); // not there
});
10 changes: 8 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
function createLookup() {
// implementation here
function createLookup(pairs) {
const lookup = {};

for (const [country, currency] of pairs) {
lookup[country] = currency;
}

return lookup;
}

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

test.todo("creates a country currency code lookup for multiple codes");
test("creates a lookup object from country-currency pairs", () => {
const input = [
["US", "USD"],
["CA", "CAD"],
];

const expected = {
US: "USD",
CA: "CAD",
};

expect(createLookup(input)).toEqual(expected);
});

test("returns an empty object when given an empty array", () => {
expect(createLookup([])).toEqual({});
});

/*

Expand Down
24 changes: 15 additions & 9 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
function parseQueryString(queryString) {
const queryParams = {};
if (queryString.length === 0) {
return queryParams;
function parseQueryString(query) {
const result = {};

if (!query) {
return result;
}
const keyValuePairs = queryString.split("&");

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
queryParams[key] = value;
// URLSearchParams treats "+" as space (" ").
// Our tests expect "+" to stay as "+" (e.g. "x=y+1"),
// so we temporarily encode "+" as "%2B" before parsing.
const safeQuery = query.replace(/\+/g, "%2B");

const params = new URLSearchParams(safeQuery);

for (const [key, value] of params) {
result[key] = value;
}

return queryParams;
return result;
}

module.exports = parseQueryString;
35 changes: 34 additions & 1 deletion Sprint-2/implement/querystring.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,43 @@
// Below is one test case for an edge case the implementation doesn't handle well.
// Fix the implementation for this test, and try to think of as many other edge cases as possible - write tests and fix those too.

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

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

test("parses a simple key=value pair", () => {
expect(parseQueryString("name=Ali")).toEqual({
name: "Ali",
});
});

test("parses multiple key=value pairs", () => {
expect(parseQueryString("name=Ali&age=30")).toEqual({
name: "Ali",
age: "30",
});
});

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

test("handles keys without values", () => {
expect(parseQueryString("flag")).toEqual({
flag: "",
});
});

test("decodes multiple URL-encoded pairs", () => {
const query = "name%20first=Sophia&name%20last=Mohamed";
const result = parseQueryString(query);

expect(result).toEqual({
"name first": "Sophia",
"name last": "Mohamed"
});
});
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(arr) {
if (!Array.isArray(arr)) {
throw new TypeError("Input must be an array");
}

// Use an object with no prototype to avoid collisions with keys like "constructor"
const counts = Object.create(null);

for (const item of arr) {
counts[item] = (counts[item] || 0) + 1;
}

return counts;
}

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,12 +23,34 @@ 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("returns an empty object for an empty array", () => {
const keys =Object.keys(tally([]));
expect(keys.length).toBe(0);
});
// Given an array with duplicate items
// When passed to tally
// Then it should return counts for each unique item

test("counts how many times each item appears", () => {
expect(tally(["a", "b", "a", "c", "b", "a"])).toEqual({
a: 3,
b: 2,
c: 1,
});
});
Comment on lines +35 to +41
Copy link
Contributor

Choose a reason for hiding this comment

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

Does tally(["constructor", "constructor"]) return what you expect?

Copy link
Author

Choose a reason for hiding this comment

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

thank you!
tally(["constructor", "constructor"]) didn’t work properly because I was using a normal {} object, so "constructor" clashed with the built-in constructor property.
I used Object.create(null) so "constructor" behaves like normal keys and doesn’t clash with JavaScript’s internal properties.


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

test("throws an error if input is not an array", () => {
expect(() => tally("not an array")).toThrow(TypeError);
expect(() => tally(123)).toThrow(TypeError);
expect(() => tally({})).toThrow(TypeError);
});
test("handles object prototype keys safely", () => {
expect(tally(["constructor", "constructor"])).toEqual({
constructor: 2,
});
});
67 changes: 58 additions & 9 deletions Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,73 @@

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

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

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

//return invertedObj;

return invertedObj;
}

// 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}
// c) What is the target return value when invert is called with {a : 1, b: 2}
//the target is to swap keys and values
{
"1": "a",
"2": "b"
}

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

//it returns an arrays of pairs
[
["a", 1],
["b", 2]
]
// it loops through the keys and the value at the same time
// d) Explain why the current return value is different from the target output
Object.entries({ a: 1, b: 2 })
//current return value
[
["a", 1],
["b", 2]
]
//It lets us easily loop through the keys and values

//for (const [key, value] of Object.entries(obj))
//Because you wrote:
//invertedObj.key = value;
//This literally creates a property named "key", not the value of the variable key.
//i need bracket notation:
//invertedObj[value] = key;
//This sets the property using the variable.

// 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;
}
console.log("Test 1:", invert({ a: 1 }));
console.log("Expected: { '1': 'a' }");
console.log("-------------");

console.log("Test 2:", invert({ a: 1, b: 2 }));
console.log("Expected: { '1': 'a', '2': 'b' }");
console.log("-------------");

console.log("Test 3:", invert({}));
console.log("Expected: {}");
console.log("-------------");

module.exports = invert;
Loading