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

// it will log out the houseNumber from the address object, but it isn't working because the property name is incorrect. The correct property name is "houseNumber", not "houseNum".
// 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 +12,4 @@ 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
@@ -1,7 +1,10 @@
// Predict and explain first...

//You’ll get an error

// 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
// The for...of loop is used to iterate over iterable objects like arrays, strings, etc.

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

for (const value of author) {
for (const value of Object.values(author)) {
console.log(value);
}
10 changes: 7 additions & 3 deletions Sprint-2/debug/recipe.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Predict and explain first...

//Prediction: The program will print the recipe title and number of servings, but instead of printing the ingredients, it will display [object Object].
//recipe is the whole object, so JavaScript will convert it to: object Object
// 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 @@ -11,5 +12,8 @@ const recipe = {
};

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

for (const ingredient of recipe.ingredients) {
console.log(ingredient);
}
7 changes: 6 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
function contains() {}
function contains(object, propertyName) {
if (object === null || typeof object !== "object" || Array.isArray(object)) {
return false;
}

return Object.hasOwn(object, propertyName);
}
module.exports = contains;
13 changes: 12 additions & 1 deletion Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,27 @@ 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 an empty object returns false", () => {
expect(contains({}, "propertyName")).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", () => {
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("returns false when the property doesn't exist", () => {
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("returns false for invalid input types", () => {
expect(contains([1, 2, 3], "0")).toBe(false);
});
Comment thread
cjyuan marked this conversation as resolved.
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(countryCurrencyPairs) {
const lookup = {};

for (const [countryCode, currencyCode] of countryCurrencyPairs) {
lookup[countryCode] = currencyCode;
}

return lookup;
}

module.exports = createLookup;
13 changes: 11 additions & 2 deletions Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
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 countryCurrencyPairs = [
["US", "USD"],
["CA", "CAD"],
];

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

Create a lookup object of key value pairs from an array of code pairs
Expand Down
25 changes: 22 additions & 3 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,29 @@ function parseQueryString(queryString) {
const keyValuePairs = queryString.split("&");

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

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

const encodedKey =
separatorIndex === -1 ? pair : pair.slice(0, separatorIndex);

const encodedValue =
separatorIndex === -1 ? "" : pair.slice(separatorIndex + 1);

const key = decodeURIComponent(encodedKey.replaceAll("+", " "));
const value = decodeURIComponent(encodedValue.replaceAll("+", " "));

if (!Object.hasOwn(queryParams, key)) {
queryParams[key] = value;
} else if (Array.isArray(queryParams[key])) {
queryParams[key].push(value);
} else {
queryParams[key] = [queryParams[key], value];
}
}
return queryParams;
}

Expand Down
13 changes: 12 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
function tally() {}
function tally(items) {
if (!Array.isArray(items)) {
throw new TypeError("Expected an array");
}
const counts = Object.create(null);

for (const item of items) {
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,7 +23,21 @@ 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({});
});

test("returns the count for each unique item", () => {
expect(tally(["a", "a", "b", "c"])).toEqual({
a: 2,
b: 1,
c: 1,
});
});

test("throws an error when passed a string", () => {
expect(() => tally("a, a, b")).toThrow(TypeError);
});

// Given an array with duplicate items
// When passed to tally
Expand Down
14 changes: 13 additions & 1 deletion Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,32 @@ 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 }
// a) Before the fix, invert({ a: 1 }) returned:
// { key: 1 }

// b) What is the current return value when invert is called with { a: 1, b: 2 }
// b) Before the fix, invert({ a: 1, b: 2 }) returned:
// { key: 2 }
// The second loop replaced the first value.

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

// c) What does Object.entries return? Why is it needed in this program?
// d) Object.entries returns an array of [key, value] pairs.
// It allows the loop to access both parts of each property.

// d) Explain why the current return value is different from the target output
// e) The original code used dot notation, which created a property
// literally named "key" instead of using the value dynamically.

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

test("swaps the keys and values in an object", () => {
expect(invert({ a: 1, b: 2 })).toEqual({
1: "a",
2: "b",
});
});

test("returns an empty object for an empty object", () => {
expect(invert({})).toEqual({});
});
15 changes: 15 additions & 0 deletions Sprint-2/stretch/count-words.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,18 @@

3. Order the results to find out which word is the most common in the input
*/
function countWords(text) {
const cleanedText = text.toLowerCase().replace(/[.,!?]/g, "");

const words = cleanedText.split(" ").filter((word) => word !== "");

const wordCounts = {};

for (const word of words) {
wordCounts[word] = (wordCounts[word] || 0) + 1;
}

return wordCounts;
}

module.exports = countWords;
20 changes: 14 additions & 6 deletions Sprint-2/stretch/mode.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,25 @@
// refactor calculateMode by splitting up the code
// into smaller functions using the stages above

function calculateMode(list) {
// track frequency of each value
let freqs = new Map();
function countFrequencies(list) {
const freqs = new Map();

for (let num of list) {
for (const num of list) {
if (typeof num !== "number") {
continue;
}

freqs.set(num, (freqs.get(num) || 0) + 1);
}

// Find the value with the highest frequency
return freqs;
}

function findHighestFrequency(frequencies) {
let maxFreq = 0;
let mode;
for (let [num, freq] of freqs) {

for (const [num, freq] of frequencies) {
if (freq > maxFreq) {
mode = num;
maxFreq = freq;
Expand All @@ -33,4 +36,9 @@ function calculateMode(list) {
return maxFreq === 0 ? NaN : mode;
}

function calculateMode(list) {
const frequencies = countFrequencies(list);
return findHighestFrequency(frequencies);
}

module.exports = calculateMode;
17 changes: 8 additions & 9 deletions Sprint-2/stretch/till.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,23 @@ function totalTill(till) {
let total = 0;

for (const [coin, quantity] of Object.entries(till)) {
total += coin * quantity;
const coinValue = parseInt(coin, 10);
total += coinValue * quantity;
}

return `£${total / 100}`;
}

const till = {
"1p": 10,
"5p": 6,
"50p": 4,
"20p": 10,
};
const totalAmount = totalTill(till);

// a) What is the target output when totalTill is called with the till object
// a) The target output is £4.4

// b) Why do we need to use Object.entries inside the for...of loop in this function?
// b) Object.entries converts the object into key-value pairs,
// allowing us to access both the coin and its quantity.

// c) What does coin * quantity evaluate to inside the for...of loop?
// c) coinValue * quantity calculates the total value
// of that type of coin.

// d) Write a test for this function to check it works and then fix the implementation of totalTill
module.exports = totalTill;
16 changes: 16 additions & 0 deletions Sprint-2/stretch/till.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const totalTill = require("./till.js");

test("calculates the total amount in the till", () => {
const till = {
"1p": 10,
"5p": 6,
"50p": 4,
"20p": 10,
};

expect(totalTill(till)).toBe("£4.4");
});

test("returns £0 for an empty till", () => {
expect(totalTill({})).toBe("£0");
});
Loading