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

// The console.log statement is attempting to use an index [0] but const address is structured as an object not an array.
// Since there is no property named 0 in the address object the console.log will return the string plus undefined.
// We must use key value pairs to get the value. To locate items from an object we can either use dot notation or bracket 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 +16,4 @@ const address = {
postcode: "XYZ 123",
};

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

// An object is not iterable by default it is a collection of keys and value pairs. This means their is no path for the for loop to follow.
// Due to this when we run this code we are going to get a type error. To fix this and log all the property values in the object;
// we must convert the object data into an array.

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

for (const value of author) {
for (const value of Object.values(author)) {
console.log(value);
}
8 changes: 7 additions & 1 deletion Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,18 @@
// Each ingredient should be logged on a new line
// How can you fix it?

// I predict this code will log: bruschetta serves 2 followed by ingredients: and then [object Object]. It won't show the actual list of ingredients.
// There are two main reasons this isn't working as intended:
// When you put ${recipe} inside a template literal, JavaScript doesn't know how to read the whole object into text, so it defaults to the placeholder [object Object]. We must point to the specific property, recipe.ingredients, instead.
// In addition to this; even if you point to recipe.ingredients, it's an array. If we want each ingredient to appear on a new line to meet the requirements, we will need to use the .join("\n") method. The \n acts as a newline character.

const recipe = {
title: "bruschetta",
serves: 2,
ingredients: ["olive oil", "tomatoes", "salt", "pepper"],
};
const formattedIngredients = recipe.ingredients.join("\n");

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
${formattedIngredients}`);
10 changes: 9 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
function contains() {}
function contains(obj, propertyName) {
// 1. Check if 'obj' is a valid object and NOT an array
if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
return false;
}

// 2. Check if the propertyName exists as a key in the object
return propertyName in obj;
}

module.exports = contains;
30 changes: 29 additions & 1 deletion Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,44 @@ 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("returns false when empty object", () => {
const input = {};
const result = contains(input, "a");
expect(result).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 the property exists in the object", () => {
const input = { firstName: "Alex", age: 30 };
const result = contains(input, "firstName");
expect(result).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 the property does not exist in the object", () => {
const input = { firstName: "Alex", age: 30 };
const result = contains(input, "lastName");
expect(result).toBe(false);
});

// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error

test("returns false when the input is an array instead of an object", () => {
const input = [1, 2, 3];
const result = contains(input, "0"); // Even though index 0 exists, it's an array
expect(result).toBe(false);
});

// 5. Given null or other types
test("returns false when the input is null or undefined", () => {
expect(contains(null, "prop")).toBe(false);
expect(contains(undefined, "prop")).toBe(false);
});
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
function createLookup(countryCurrencyPairs) {
const lookup = {};

for (const pair of countryCurrencyPairs) {
const country = pair[0];
const currency = pair[1];

lookup[country] = currency;
}

return lookup;
}

module.exports = createLookup;
37 changes: 34 additions & 3 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,44 @@
function parseQueryString(queryString) {
const queryParams = {};
if (queryString.length === 0) {
if (typeof queryString !== "string") {
return queryParams;
}

if (queryString.startsWith("?")) {
queryString = queryString.substring(1);
}

if (queryString.trim() === "") {
return queryParams;
}

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

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

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

let key = pair;
let value = "";

if (equalIndex !== -1) {
key = pair.substring(0, equalIndex);
value = pair.substring(equalIndex + 1);
}

key = decodeURIComponent(key);
value = decodeURIComponent(value);

if (queryParams.hasOwnProperty(key)) {
if (Array.isArray(queryParams[key])) {
queryParams[key].push(value);
} else {
queryParams[key] = [queryParams[key], value];
}
} else {
queryParams[key] = value;
}
}

return queryParams;
Expand Down
46 changes: 44 additions & 2 deletions Sprint-2/implement/querystring.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,52 @@
// 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",
equation: "x=y+1",
});
});

test("parses querystring values missing = sign", () => {
expect(parseQueryString("userId=101&username=jdoe&isActive")).toEqual({
userId: "101",
username: "Aokorefe",
isActive: "",
});
});

test("parses querystring values containing no key and value but only =", () => {
expect(parseQueryString("=&priority=high&taskId=42&=&=")).toEqual({
priority: "high",
taskId: "42",
});
});

test("parses querystring with encoded keys and values", () => {
expect(
parseQueryString(
"query=web%20design&location=San%20Francisco&query=ui%20ux"
)
).toEqual({
query: ["web design", "ui ux"],
location: "London",
});
});

test("parses querystring values containing repetitive keys", () => {
expect(
parseQueryString("tag=frontend&count=10&tag=backend&tag=devops&count=20")
).toEqual({
tag: ["frontend", "backend", "devops"],
count: ["10", "20"],
});
});

test("parses querystring with leading ?", () => {
expect(parseQueryString("?search=javascript&sort=asc")).toEqual({
search: "javascript",
sort: "asc",
});
});
16 changes: 15 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
function tally() {}
function tally(items) {
// Check for valid input
if (!Array.isArray(items)) {
throw new Error("Input must be an array");
}

const counts = {};

for (const item of items) {
// If the item exists, increment; otherwise, initialize to 1
counts[item] = (counts[item] || 0) + 1;
}

return counts;
}

module.exports = tally;
8 changes: 7 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,18 @@ 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 returns correct counts", () =>
expect(tally(["a", "a", "b", "c"])).toEqual({ a: 2, b: 1, c: 1 }));

// Given an invalid input like a string
// When passed to tally
// Then it should throw an error
test("tally throws an error when passed a string", () => {
expect(() => tally("not an array")).toThrow();
});
16 changes: 15 additions & 1 deletion Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,34 @@ function invert(obj) {
const invertedObj = {};

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

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}

// { "1": "a", "2": "b" }

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

// Object.entries returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
// It is needed in this program to iterate over the key-value pairs of the input object and swap them to create the inverted object.

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

// The current return value is different from the target output because the code is assigning
// the value to a property named "key" in the invertedObj, instead of using the actual key from the input object.
// This results in only the last key-value pair being stored in the invertedObj, and it does not correctly swap the keys and values as intended.

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

describe("invert()", () => {
test("inverts a single key-value pair", () => {
expect(invert({ a: 1 })).toEqual({ 1: "a" });
});

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

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

test("inverts an object with string values", () => {
expect(invert({ first: "John", last: "Doe" })).toEqual({
Alex: "first",
Doe: "last",
});
});
});
2 changes: 1 addition & 1 deletion Sprint-3/alarmclock/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
Expand Down
Loading