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,4 +1,8 @@
// Predict and explain first...
// address is an object, not an array
// address[0] looks for a property named "0",
// which doesn't exist → returns undefined
// So the log will say: My house number is undefined

// This code should log out the houseNumber from the address object
// but it 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}`);
8 changes: 6 additions & 2 deletions Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
// Predict and explain first...
// The 'author' variable is an object, not an array or string.
// for..of loops require an iterable, but plain objects are not iterable.
// This will throw a TypeError: author is not iterable.
// Nothing will be logged to the console.

// 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 +15,6 @@ const author = {
alive: true,
};

for (const value of author) {
for (const value of Object.values(author)) {
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,4 +1,8 @@
// Predict and explain first...
// The template literal ${recipe} attempts to convert the entire object to a string.
// Because objects aren't strings, it will log: "[object Object]".
// It also fails to access the specific 'ingredients' array or loop through them.
// The result will be one confusing line instead of a formatted list.

// This program should log out the title, how many it serves and the ingredients.
// Each ingredient should be logged on a new line
Expand All @@ -10,6 +14,9 @@ const recipe = {
ingredients: ["olive oil", "tomatoes", "salt", "pepper"],
};

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

for (const ing of recipe.ingredients) {
console.log(` - ${ing}`);
}
12 changes: 11 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
function contains() {}
function contains(object, propertyName) {
// return false if object is null/defined or not an object
if (object == null) return false;
// typeof check + reject arrays
if (typeof object !== "object") return false;
if (Array.isArray(object)) return false;

// Use Object.hasOwn to check only own properties

return Object.hasOwn(object, propertyName);
}

module.exports = contains;
22 changes: 21 additions & 1 deletion Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,40 @@ 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 when the property exists in the object", () => {
expect(contains({ a: 1, b: 2 }, "a")).toBe(true);
expect(contains({ a: 1, b: 2 }, "b")).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);
expect(contains({}, "toString")).toBe(false);
});

// Given an object with properties
// When passed to contains with an existing property name
// Then it should return true
test("returns true for existing property name", () => {
expect(contains({ name: "Alex" }, "name")).toBe(true);
expect(contains({ id: 42 }, "id")).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 for non-existent property name", () => {
expect(contains({ name: "Alex", age: 42 }, "email")).toBe(false);
expect(contains({ age: 54 }, "name")).toBe(false);
});

// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error
test("handles invalid parameters like an array", () => {
expect(contains([], "length")).toBe(false);
expect(contains(123, "length")).toBe(false);
expect(contains("string", "length")).toBe(false);
});
15 changes: 13 additions & 2 deletions Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
function createLookup() {
// implementation here
function createLookup(pairs) {
// Implementation goes here
// Creates an empty object to store the lookup results
// country → currency
const lookup = {};
// Loop through each pair in the input array
for (const [country, currency] of pairs) {
// Use the country code as the function key
// Assigns the correspoding currency code as the value
lookup[country] = currency;
}
// returns the completed lookup object
return lookup;
}

module.exports = createLookup;
14 changes: 12 additions & 2 deletions Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
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 pairs = [
["US", "USD"],
["CA", "CAD"],
];
const result = createLookup(pairs);

expect(result).toEqual({
US: "USD",
CA: "CAD",
});
});
/*

Create a lookup object of key value pairs from an array of code pairs
Expand Down
30 changes: 23 additions & 7 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,32 @@
function parseQueryString(queryString) {
const queryParams = {};
if (queryString.length === 0) {

// Handle empty query string
if (!queryString || queryString === "?") {
return queryParams;
}
const keyValuePairs = queryString.split("&");

for (const pair of keyValuePairs) {
const [key, value] = pair.split("=");
queryParams[key] = value;
}
// Remove leading ? if present
const cleaned = queryString.startsWith("?")
? queryString.slice(1)
: queryString;

// Split into segments and ignore empty ones
const segments = cleaned.split("&").filter(Boolean);

return queryParams;
for (const segment of segments) {
// Split only on the first =, but everything after is a value
const eqIndex = segment.indexOf("=");

const key = eqIndex === -1 ? segment : segment.slice(0, eqIndex);
const value = eqIndex === -1 ? "" : segment.slice(eqIndex + 1);

if (key) {
// Decode percent-encoded characters in both key and value
queryParams[decodeURIComponent(key)] = decodeURIComponent(value);
}
}

return queryParams;
}
module.exports = parseQueryString;
52 changes: 50 additions & 2 deletions Sprint-2/implement/querystring.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,58 @@
// 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("handles multiple parameters", () => {
expect(parseQueryString("name=Alex&age=25&city=London")).toEqual({
name: "Alex",
age: "25",
city: "London",
});
});

test("handles empty value (key=)", () => {
expect(parseQueryString("search=&page=3")).toEqual({
search: "",
page: "3",
});
});

test("handles key without value", () => {
expect(parseQueryString("debug&sort=asc")).toEqual({
debug: "",
sort: "asc",
});
});

test("handles leading question mark", () => {
expect(parseQueryString("?q=javascript&lang=en")).toEqual({
q: "javascript",
lang: "en",
});
});

test("returns empty object when input is empty or just ?", () => {
expect(parseQueryString("")).toEqual({});
expect(parseQueryString("?")).toEqual({});
});

test("ignores trailing &", () => {
expect(parseQueryString("a=1&b=2&")).toEqual({
a: "1",
b: "2",
});
});

test("ignores repeated &", () => {
expect(parseQueryString("x=10&&y=20")).toEqual({
x: "10",
y: "20",
});
});
22 changes: 21 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,23 @@
function tally() {}
function tally(arr) {
// Check if the input is not an array
if (!Array.isArray(arr)) {
// If it's not an array, stop the function and return an error message

throw new Error("Input must be an array");
}

// Create an empty object with no interited properties to store
// This prevents conflicts with built in properties like "toString"
const counts = Object.create(null);

// Loop through each item in the array one by one
for (const item of arr) {
// If the item already exists in counts, add 1 to it
// If it doesn't exist yet (undefined), start it at 0 then add 1
counts[item] = (counts[item] || 0) + 1;
}
// Return the finished counts object once all items have been tallied
return counts;
}

module.exports = tally;
28 changes: 27 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,42 @@ 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
test("tally returns an object containing the count for each unique item", () => {
expect(tally(["a", "a", "b", "c"])).toEqual({
a: 2,
b: 1,
c: 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 a single item
// When passed to tally
// Then it should return a count of 1 for that item
test("tally on an array with one item returns count of 1", () => {
expect(tally(["a"])).toEqual({
a: 1,
});
});

// Given an array with duplicate items
// When passed to tally
// Then it should return counts for each unique item
test("tally counts duplicate items correctly", () => {
expect(tally(["a", "a", "a"])).toEqual({
a: 3,
});
});

// 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", () => {
expect(() => tally("abc")).toThrow("Input must be an array");
});
16 changes: 15 additions & 1 deletion Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,37 @@
// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}

function invert(obj) {
// Check if the input is not an object
if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
throw new Error("Input must be an object");
}
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 }
// The current return value when invert is called with { a : 1 } is { key:1 }

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

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

// c) What does Object.entries return? Why is it needed in this program?
// Object.entries converts an object into an array of [key, value] pairs,
// it's needed so you can loop through both the key and value at the same time

// d) Explain why the current return value is different from the target output
// The bug is invertedObj.key = value - dot notation sets a literal key called "key",
// instead of using the variable. It also overwrites itseld on every loop iteration,
// so you only ever get the last value.

// e) Fix the implementation of invert (and write tests to prove it's fixed!)
// Fixed implementation of invert and added tests cases to prove it's fixed.
Loading