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...

// After i run it will be undefined or throw an error because this is an object not an array to use the square bracket.
// 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}`);
4 changes: 2 additions & 2 deletions Sprint-2/debug/author.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Predict and explain first...

// Plain objects are not iterable so we have to use some of the built in object methods.
// 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 +11,6 @@ const author = {
alive: true,
};

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

// I think I have to use index to log out every ingredient as it is an array.
// 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 +11,9 @@ const recipe = {
};

console.log(`${recipe.title} serves ${recipe.serves}
ingredients:
ingredients
${recipe.ingredients[0]}:
${recipe.ingredients[1]}:
${recipe.ingredients[2]}:
${recipe.ingredients[3]}:
${recipe}`);
11 changes: 10 additions & 1 deletion Sprint-2/implement/contains.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
function contains() {}
function contains(obj, key) {

if(typeof obj !== "object" || obj === null || Array.isArray(obj)){
return false;
}

return obj.hasOwnProperty(key);


}

module.exports = contains;
35 changes: 30 additions & 5 deletions Sprint-2/implement/contains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ E.g. contains({a: 1, b: 2}, 'a') // returns true
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'
as the object doesn't contain a key of 'c'
*/

// Acceptance criteria:
Expand All @@ -20,16 +20,41 @@ 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 an empty object returns false", () => {
expect(contains({}, "a")).toBe(false);
});

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

test("contains array-like object,invalid object and null returns false",() => {
expect(contains([], "a")).toBe(false);
expect(contains(123, "a")).toBe(false);
expect(contains(null, "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 for existent property", () => {
const obj = {a: 1, b: 2}
expect(contains(obj, "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 for non existent properties", () => {
const obj1= {a: 1, b:2}
expect(contains("c")).toBe(false);
});






// Given invalid parameters like an array
// When passed to contains
// Then it should return false or throw an error
7 changes: 6 additions & 1 deletion Sprint-2/implement/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
function createLookup() {
function createLookup(pairs) {
// implementation here
const lookup = {};
for(const [countryCode, currencyCode]of pairs){
lookup[countryCode] = currencyCode;
}
return lookup;
}

module.exports = createLookup;
11 changes: 10 additions & 1 deletion Sprint-2/implement/lookup.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
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']];

const expected = {
US: 'USD',
CA: 'CAD',
}
expect(createLookup(countryCurrencyPairs)).toEqual(expected);
});


/*

Expand Down
14 changes: 11 additions & 3 deletions Sprint-2/implement/querystring.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,19 @@ function parseQueryString(queryString) {
const keyValuePairs = queryString.split("&");

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

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

if (idx === -1) {
// No '=' found, treat entire pair as key with empty value
queryParams[pair] = "";
} else {
const key = pair.substring(0, idx);
const value = pair.substring(idx + 1);
queryParams[key] = value;
}

return queryParams;
}
return queryParams;
}

module.exports = parseQueryString;
22 changes: 21 additions & 1 deletion Sprint-2/implement/querystring.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,30 @@
// 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",
});
});
test("parses empty values", () =>{
expect(parseQueryString("a=&b=2")).toEqual({a:"",b:"2"})
});

test("parses containing =",() => {
expect(parseQueryString("equation=x=y+1")).toEqual({equation: "x=y+1"})
});


test("parses empty string", () => {
expect(parseQueryString("")).toEqual({});
});

test("parses multiple pairs including empty value", () => {
expect(parseQueryString("a=1&b=&c=3")).toEqual({ a: "1", b: "", c: "3" });
});

test("parses repeated keys (last one wins)", () => {
expect(parseQueryString("a=1&a=2")).toEqual({ a: "2" });
});
19 changes: 18 additions & 1 deletion Sprint-2/implement/tally.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
function tally() {}
function tally(items) {
if (!Array.isArray(items)) {
throw new Error("Input must be an array");
}

const result = {};

for (const item of items) {
if (result[item]) {
result[item] += 1;
} else {
result[item] = 1;
}
}

return result;

}

module.exports = tally;
24 changes: 23 additions & 1 deletion Sprint-2/implement/tally.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,34 @@ 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");


// Empty array → empty object
test("tally on an empty array returns an empty object", () => {
expect(tally([])).toEqual({});
});


test("tally counts occurrences of items", () => {
expect(tally(["a", "a", "b", "c"])).toEqual({
a: 2,
b: 1,
c: 1
});
});
// Given an array with duplicate items
// When passed to tally
// Then it should return counts for each unique item
test("tally works for a single repeated item", () => {
expect(tally(["x", "x", "x"])).toEqual({ x: 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("not an array")).toThrow("Input must be an array");
});



15 changes: 14 additions & 1 deletion Sprint-2/interpret/invert.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,36 @@
// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}

function invert(obj) {
if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
throw new Error("Input must be a non-null object");
}
const invertedObj = {};

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

return invertedObj;
}

module.exports = invert

// 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 }
//Only the last value remains, so it returns:
//{ 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?
// as it is a built in method Object.entries returns an array of [key, value] pairs.
//It is needed so we can loop through both keys and values easily.

// d) Explain why the current return value is different from the target output
//Because the code uses invertedObj.key (a literal property named "key") instead of using the variable key.
//It overwrites the same property instead of swapping keys and values

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

test("inverts a simple object", () => {
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("inverts string values", () => {
expect(invert({ x: "apple", y: "banana" })).toEqual({
apple: "x",
banana: "y"
});
});

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

test("throws an error for null", () => {
expect(() => invert(null)).toThrow("Input must be a non-null object");
});

test("throws an error for arrays", () => {
expect(() => invert([1, 2, 3])).toThrow("Input must be a non-null object");
});
3 changes: 3 additions & 0 deletions Sprint-2/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@
"scripts": {
"test": "jest"
},
"type": "module",

"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^29.7.0"
}

}
30 changes: 30 additions & 0 deletions Sprint-2/stretch/count-words.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,33 @@

3. Order the results to find out which word is the most common in the input
*/
function countWords(str){
str = str.toLowerCase();

// 2. Remove punctuation (anything that is not a letter, number, or space)
str = str.replace(/[^\w\s]/g, '');

// 3. Split the string into words
const words = str.split(/\s+/);

// 4. Create an object to store word counts
const wordCounts = {};

// 5. Count each word
for (const word of words) {
if (word === '') continue; // skip empty strings (in case of multiple spaces)
if (wordCounts[word]) {
wordCounts[word] += 1;
} else {
wordCounts[word] = 1;
}
}

// 6. Optional: Sort by frequency (most common first)
const sortedWordCounts = Object.fromEntries(
Object.entries(wordCounts).sort((a, b) => b[1] - a[1])
);
return sortedWordCounts;
};

console.log(countWords("You and me, and you!"));
Loading