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

// This code should log out the houseNumber from the address object

// but it isn't working...

// Fix anything that isn't working

const address = {
Expand All @@ -12,4 +14,4 @@ const address = {
postcode: "XYZ 123",
};

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

// 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 problem is that the for...of loop is being used on an object,
// which is not iterable. Instead, we should use Object.values() to get an array of the object's values and then iterate over that array.

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

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

// 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?
// The problem is that the recipe object is being logged directly, which will not display the ingredients in the desired format.
// Instead, we should iterate over the ingredients array and log each ingredient on a new line.

const recipe = {
title: "bruschetta",
Expand All @@ -11,5 +14,7 @@ const recipe = {
};

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
${recipe}`);
ingredients:`);
recipe.ingredients.forEach((ingredient) => {
console.log(`- ${ingredient}`);
});
10 changes: 8 additions & 2 deletions Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
function contains() {}
function contains(object, propertyName) {
if (Array.isArray(object)) {
return false;
}

module.exports = contains;
return Object.hasOwn(object, propertyName);
}

module.exports = contains;
14 changes: 13 additions & 1 deletion Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,28 @@ 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], "propertyName")).toBe(false);
});
12 changes: 9 additions & 3 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;
module.exports = createLookup;
12 changes: 11 additions & 1 deletion Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +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",
});
});

/*

Expand Down
26 changes: 24 additions & 2 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,35 @@
function parseQueryString(queryString) {
const queryParams = {};

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;
}

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
16 changes: 14 additions & 2 deletions Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
function tally() {}
function tally(items) {
if (!Array.isArray(items)) {
throw new TypeError("Expected an array");
}

module.exports = tally;
const counts = {};

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
28 changes: 13 additions & 15 deletions Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,27 @@
// Let's define how invert should work

// Given an object
// When invert is passed this object
// Then it should swap the keys and values in the object

// 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;
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({});
});
20 changes: 20 additions & 0 deletions Sprint-2/stretch/count-words.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,23 @@

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;
22 changes: 22 additions & 0 deletions Sprint-2/stretch/count-words.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const countWords = require("./count-words.js");

test("counts how many times each word appears", () => {
expect(countWords("you and me and you")).toEqual({
you: 2,
and: 2,
me: 1,
});
});

test("ignores capital letters and punctuation", () => {
expect(countWords("Hello, hello! How are you?")).toEqual({
hello: 2,
how: 1,
are: 1,
you: 1,
});
});

test("returns an empty object for an empty string", () => {
expect(countWords("")).toEqual({});
});
36 changes: 22 additions & 14 deletions Sprint-2/stretch/mode.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,37 @@
// 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 frequencies = new Map();

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

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

// Find the value with the highest frequency
let maxFreq = 0;
return frequencies;
}

function findMostFrequent(frequencies) {
let highestFrequency = 0;
let mode;
for (let [num, freq] of freqs) {
if (freq > maxFreq) {
mode = num;
maxFreq = freq;

for (const [number, frequency] of frequencies) {
if (frequency > highestFrequency) {
highestFrequency = frequency;
mode = number;
}
}

return maxFreq === 0 ? NaN : mode;
return highestFrequency === 0 ? NaN : mode;
}

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

module.exports = calculateMode;
module.exports = calculateMode;
Loading
Loading