Skip to content
3 changes: 2 additions & 1 deletion Sprint-2/debug/address.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ const address = {
postcode: "XYZ 123",
};

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

// 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
// Because objects are not iterable, so they need to be converted to arrays so as we can loop through them so, with Object.entries() method as this method converts the objects into key and value pairs within an array.

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

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

// so the first recipe.title prints the correct title, the second recipe.serves also prints the correct number of serves but the last recipe in template literals will throw error or perhaps undefined as recipe is an object and needs different method to access it. so basically inorder to access the key and values inside an object, it should be accessed by using object name followed by a dot and one of the values or keys inside it (whatever we want to use).
// 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 @@ -9,7 +9,14 @@ const recipe = {
serves: 2,
ingredients: ["olive oil", "tomatoes", "salt", "pepper"],
};

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
let recipeEntries = Object.entries(recipe);
for (const [reicpeKey, recipeValue] of recipeEntries) {
if (reicpeKey === "ingredients") {
console.log("Ingredients:");
for (const ingredient of recipeValue) {
console.log(ingredient);
}
} else {
console.log(`${reicpeKey}: ${recipeValue}`);
}
}
9 changes: 8 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
function contains() {}
function contains(obj, key) {
for (const currentKey of Object.keys(obj)) {
if (currentKey === key) {
return true;
}
}
return false;
}

module.exports = contains;
20 changes: 17 additions & 3 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,40 @@ as the object contains a key of 'a'
E.g. contains({a: 1, b: 2}, 'c') // returns false
as the object doesn't contains a key of 'c'
*/
console.log("THIS IS THE REAL contains.js FILE");

// Acceptance criteria:

// 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("contains both existent and non-existent properties, returns true if existent or false if otherwise", () => {
expect(contains({ z: 2, e: 5 }, "a")).toBe(false);
expect(contains({ y: 6, x: 3, s: 5 }, "s")).toBe(true);
});

// Given an empty object
// When passed to contains
// Then it should return false
test.todo("contains on empty object returns false");
test("returns false for an empty object", () => {
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("returns true when object contains the property", () => {
expect(contains({ a: 1, b: 3 }, "a")).toBe(true);
});
// Given an object with properties
// When passed to contains with a non-existent property name
// Then it should return false

test("returns false when object does not contain the property", () => {
expect(contains({ w: 1, x: 8 }, "r")).toBe(false);
});
// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error
test("returns false for invalid parameters like an array", () => {
expect(contains([], "a")).toBe(false);
});
17 changes: 15 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
function createLookup() {
// implementation here
function createLookup(countrycurrency) {
const lookup = {}; // lookup object is created empty to store the new keys and values mapped from the function
countrycurrency.map(function ([country, currency]) {
// maps every keys and values passed as argument in countrycurrency and stores to the variable names of country and currency
console.log(`${country}: ${currency}`);
lookup[country] = currency; // this lookup object is then used to store the already mapped keys and values of the countrycurrency
});
return lookup;
}
console.log(
createLookup([
["US", "USD"],
["UAE", "AED"],
["ERI", "ERN"],
])
);

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

test.todo("creates a country currency code lookup for multiple codes");
test("creates a country currency code lookup object for multiple codes", () => {
const result = createLookup([
["US", "USD"],
["UAE", "AED"],
["ERI", "ERN"],
]);

expect(result).toEqual({
US: "USD",
UAE: "AED",
ERI: "ERN",
});
});

test("prints country and currency vertically", () => {
console.log = jest.fn(); //mocks the console.log which is used to print out only returned values, but since this test only checks the printed output but not returned values, we do mock the console.log to check the printed output

createLookup([
["US", "USD"],
["CA", "CAD"],
]);

expect(console.log).toHaveBeenCalledWith("US: USD");
expect(console.log).toHaveBeenCalledWith("CA: CAD");
});

/*

Expand Down
38 changes: 36 additions & 2 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,48 @@ function parseQueryString(queryString) {
if (queryString.length === 0) {
return queryParams;
}

const keyValuePairs = queryString.split("&");

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
queryParams[key] = value;
if (!pair) continue; // ignore empty pairs

const index = pair.indexOf("=");

let rawKey, rawValue;

if (index === -1) {
rawKey = pair;
rawValue = "";
} else {
rawKey = pair.slice(0, index);
rawValue = pair.slice(index + 1);
}

// Replace '+' with space
rawValue = rawValue.replace(/\+/g, " ");
rawKey = rawKey.replace(/\+/g, " ");

// Decode percent-encoding
rawKey = decodeURIComponent(rawKey);
rawValue = decodeURIComponent(rawValue);

const key = rawKey;
const value = rawValue;

// Handle repeated keys → array
if (queryParams.hasOwnProperty(key)) {
if (!Array.isArray(queryParams[key])) {
queryParams[key] = [queryParams[key]];
}
queryParams[key].push(value);
} else {
queryParams[key] = value;
}
}

return queryParams;
}
console.log(parseQueryString("key=value1&key=value2&key=value3&foo=bar"));

module.exports = parseQueryString;
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");
const counts = Object.create(null);
if (arr.length === 0) {
return counts;
}
for (const item of arr) {
if (typeof item !== "string" || !/^[A-Za-z0-9]+$/.test(item)) {
throw new Error("Please Enter Valid Input!");
}
counts[item] = (counts[item] ?? 0) + 1;
}
return counts;
}

module.exports = tally;
41 changes: 29 additions & 12 deletions Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,33 @@ const tally = require("./tally.js");
// Given a function called tally
// When passed an array of items
// Then it should return an object containing the count for each unique item
describe("tally", () => {
test("Given an array of items, returns counts for each unique item", () => {
const input = ["apple", "banana", "apple", "orange", "banana", "apple"];
const expected = { apple: 3, banana: 2, orange: 1 };
expect(tally(input)).toEqual(expected);
});
// Given an empty array
// When passed to tally
// Then it should return an empty object
test("tally on an empty array returns an empty object", () => {
expect([]).toEqual({});
});

// 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");

// Given an array with duplicate items
// When passed to tally
// Then it should return counts for each unique item

// Given an invalid input like a string
// When passed to tally
// Then it should throw an error
// 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 items, returns counts for each unique item", () => {
const input = ["x", "x", "y", "x", "y"];
const expected = { x: 3, y: 2 };
expect(tally(input)).toEqual(expected);
});
// Given an invalid input like a string
// When passed to tally
// Then it should throw an error
test("Given an array containing an invalid item, throws an Error", () => {
expect(() => tally(["valid", "hello world"])).toThrow(
"Please Enter Valid Input!"
);
});
});
51 changes: 39 additions & 12 deletions Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,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;
// Validate input type
if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
throw new Error("Input must be an object");
}

return invertedObj;
}
const entries = Object.entries(obj);
if (entries.length === 0) return {};

// a) What is the current return value when invert is called with { a : 1 }
// take only the values
const values = entries.map(([_, v]) => v);

// b) What is the current return value when invert is called with { a: 1, b: 2 }
// Detect duplicate values
const hasDuplicate = new Set(values).size !== values.length;
if (hasDuplicate) {
throw new Error("Values cannot be duplicated");
}

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

// c) What does Object.entries return? Why is it needed in this program?
for (const [key, value] of entries) {
// Validate key and value types
if (
(typeof key !== "string" && typeof key !== "number") ||
(typeof value !== "string" && typeof value !== "number")
) {
throw new Error("Keys and values must be a string or a number");
}

// d) Explain why the current return value is different from the target output
inverted[value] = key;
}

return inverted;
}
module.exports = invert;

// e) Fix the implementation of invert (and write tests to prove it's fixed!)
// a) What is the current return value when invert is called with { a : 1 }
// the current value is 1
// b) What is the current return value when invert is called with { a: 1, b: 2 }
// the current return value at this call is 2
// c) What is the target return value when invert is called with {a : 1, b: 2}
// the target return value at this call is to supposed to be 'b'
// d) What does Object.entries return? Why is it needed in this program?
// Object.entries is used because both key and value are needed to be returned from the loop
// e) Explain why the current return value is different from the target output
// it's because the code in the line 13 is only returning single literal property named "key" on every loop iteration, so each assignment overwrites the previous one and the final object ends up with { key: 2 } but the intended inverted output requires using the loop variables as property names (dynamic keys) so each iteration creates a distinct property (for example invertedObj[value] = key), producing separate entries like { 1: 'a', 2: 'b' } instead of repeatedly writing to the same "key" property which the current function is doing
// f) Fix the implementation of invert (and write tests to prove it's fixed!)
// Above is the fixed function
59 changes: 59 additions & 0 deletions Sprint-2/interpret/invert.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const invert = require("./invert");

test("inverts a simple object", () => {
const input = { a: "x", b: "y" };
const expected = { x: "a", y: "b" };
expect(invert(input)).toEqual(expected);
});

test("inverts an object with number values", () => {
const input = { a: 1, b: 2 };
const expected = { 1: "a", 2: "b" };
expect(invert(input)).toEqual(expected);
});

test("accepts empty string as a key", () => {
const input = { "": "x" };
const expected = { x: "" };
expect(invert(input)).toEqual(expected);
});

test("returns an empty object when input is empty", () => {
expect(invert({})).toEqual({});
});

test("throws when input is null", () => {
expect(() => invert(null)).toThrow("Input must be an object");
});

test("throws when input is not an object", () => {
expect(() => invert("hello")).toThrow("Input must be an object");
expect(() => invert(123)).toThrow("Input must be an object");
expect(() => invert(true)).toThrow("Input must be an object");
});

test("throws when input is an array", () => {
expect(() => invert(["a", "b"])).toThrow("Input must be an object");
});

test("throws when a value is not a string or number", () => {
const obj = { a: {} };
expect(() => invert(obj)).toThrow(
"Keys and values must be a string or a number"
);
});

test("throws when values are duplicated (string)", () => {
const obj = { a: "x", b: "y", c: "x" };
expect(() => invert(obj)).toThrow("Values cannot be duplicated");
});

test("throws when numeric values are duplicated", () => {
const obj = { a: 1, b: 2, c: 1 };
expect(() => invert(obj)).toThrow("Values cannot be duplicated");
});

test("duplicate keys are overwritten by JavaScript before reaching invert()", () => {
const obj = { a: "x", a: "y" }; // JS overwrites first 'a'
expect(invert(obj)).toEqual({ y: "a" });
});
Loading