From 97456f541997dea7eed6a51d763df398c9b0ab2c Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Fri, 14 Feb 2025 16:21:41 +0100 Subject: [PATCH 01/15] solution traffic light 1 --- .../1-traffic-light/traffic-light-1.js | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/Week1/prep-exercises/1-traffic-light/traffic-light-1.js b/Week1/prep-exercises/1-traffic-light/traffic-light-1.js index f1d9169..6acee27 100644 --- a/Week1/prep-exercises/1-traffic-light/traffic-light-1.js +++ b/Week1/prep-exercises/1-traffic-light/traffic-light-1.js @@ -1,16 +1,24 @@ -"use strict"; +'use strict'; /** * The `state` property says what the traffic light's state (i.e. colour) is at * that moment. */ const trafficLight = { - state: "green", + state: 'green', }; let rotations = 0; while (rotations < 2) { const currentState = trafficLight.state; - console.log("The traffic light is on", currentState); + if (currentState === 'green') { + trafficLight.state = 'orange'; + } else if (currentState == 'orange') { + trafficLight.state = 'red'; + } else if (currentState == 'red') { + trafficLight.state = 'green'; + rotations++; + } + console.log('The traffic light is on', currentState); // TODO // if the color is green, turn it orange From 6132cc70f6b63a92c94ea411306e692a7e17ad2a Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Fri, 14 Feb 2025 16:25:14 +0100 Subject: [PATCH 02/15] solution traffic light 2 --- .../1-traffic-light/traffic-light-2.js | 50 +++++++++++++++++-- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/Week1/prep-exercises/1-traffic-light/traffic-light-2.js b/Week1/prep-exercises/1-traffic-light/traffic-light-2.js index 8c6ba95..715fc3c 100644 --- a/Week1/prep-exercises/1-traffic-light/traffic-light-2.js +++ b/Week1/prep-exercises/1-traffic-light/traffic-light-2.js @@ -1,18 +1,28 @@ -"use strict"; +'use strict'; /** * The `possibleStates` property define the states (in this case: colours) * in which the traffic light can be. * The `stateIndex` property indicates which of the possible states is current. */ const trafficLight = { - possibleStates: ["green", "orange", "red"], + possibleStates: ['green', 'orange', 'red'], stateIndex: 0, }; let cycle = 0; + while (cycle < 2) { const currentState = trafficLight.possibleStates[trafficLight.stateIndex]; - console.log("The traffic light is on", currentState); + + if (currentState == 'green') { + trafficLight.stateIndex = 1; + } else if (currentState == 'orange') { + trafficLight.stateIndex = 2; + } else if (currentState == 'red') { + trafficLight.stateIndex = 0; + cycle++; + } + console.log('The traffic light is on', currentState); // TODO // if the color is green, turn it orange @@ -20,6 +30,40 @@ while (cycle < 2) { // if the color is red, add 1 to cycles and turn it green } +// do while loop + +// do { +// const currentState = trafficLight.possibleStates[trafficLight.stateIndex]; +// if (currentState == 'green') { +// trafficLight.stateIndex = 1 +// } else if (currentState == "orange") { +// trafficLight.stateIndex = 2 +// } else if (currentState == 'red') { +// trafficLight.stateIndex = 0 +// cycle++ +// } +// console.log("The traffic light is on", currentState); + +// } while (cycle < 2) + +//for loop + +// for (let i = 0; i < 2;) { +// const currentState = trafficLight.possibleStates[trafficLight.stateIndex]; +// if (currentState == 'green') { +// trafficLight.stateIndex = 1 +// } else if (currentState == "orange") { +// trafficLight.stateIndex = 2 +// } else if (currentState == 'red') { +// trafficLight.stateIndex = 0 +// i++ +// } +// console.log("The traffic light is on", currentState); + +// } + +// In a for loop, I use i instead of cycle, so I treat it like a cycle. I want to increase it when the color is red. + /** * The output should be: From bf1d13520e088e20ffbb14603e76303bce21302f Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Mon, 17 Feb 2025 12:02:47 +0100 Subject: [PATCH 03/15] Solve first question --- Week1/practice-exercises/1-remove-the-comma.js | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/Week1/practice-exercises/1-remove-the-comma.js b/Week1/practice-exercises/1-remove-the-comma.js index b71cffd..5538994 100644 --- a/Week1/practice-exercises/1-remove-the-comma.js +++ b/Week1/practice-exercises/1-remove-the-comma.js @@ -1,14 +1,19 @@ /** * We want to remove the comma's in the given string (myString), replace them with a space and log it to the console. - * - * The end result should be: + * + * The end result should be: * hello this is a difficult to read sentence */ let myString = 'hello,this,is,a,difficult,to,read,sentence'; +myString = myString.replaceAll(',', ' '); +// myString = myString.split(',').join(' ') /* --- Code that will test your solution, do NOT change. Write above this line --- */ -console.assert(myString === 'hello this is a difficult to read sentence', 'There is something wrong with your solution'); \ No newline at end of file +console.assert( + myString === 'hello this is a difficult to read sentence', + 'There is something wrong with your solution' +); From 55fd3e9274753781852d3ce608c1f27ca50aaa7b Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Mon, 17 Feb 2025 12:04:33 +0100 Subject: [PATCH 04/15] Solve second question --- Week1/practice-exercises/2-even-odd-reporter.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Week1/practice-exercises/2-even-odd-reporter.js b/Week1/practice-exercises/2-even-odd-reporter.js index 6edf23e..bffd6ad 100644 --- a/Week1/practice-exercises/2-even-odd-reporter.js +++ b/Week1/practice-exercises/2-even-odd-reporter.js @@ -7,3 +7,10 @@ * If it's even, log to the console The number [PUT_NUMBER_HERE] is even!. */ +for (let i = 0; i <= 20; i++) { + if (i % 2 === 0) { + console.log(` The number ${i} is even!.`); + } else { + console.log(` The number ${i} is odd!.`); + } +} From e7a363d25194bd5d48d7a73b0c82b32b53c99f72 Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Wed, 19 Feb 2025 10:32:07 +0100 Subject: [PATCH 05/15] Solve third question --- Week1/practice-exercises/3-recipe-card.js | 41 +++++++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/Week1/practice-exercises/3-recipe-card.js b/Week1/practice-exercises/3-recipe-card.js index 24bcb54..5ab6c9c 100644 --- a/Week1/practice-exercises/3-recipe-card.js +++ b/Week1/practice-exercises/3-recipe-card.js @@ -1,14 +1,49 @@ /** * Ever wondered how to make a certain meal? Let's create a recipe list with JavaScript! - * + * * Declare a variable that holds an empty object literal (your meal recipe). * Give the object 3 properties: a title (string), a servings (number) and an ingredients (array of strings) property. * Log each property out separately, using a loop (for, while or do/while) - * + * * Expected result: - * + * * Meal name: Omelette * Serves: 2 * Ingredients: 4 eggs, 2 strips of bacon, 1 tsp salt/pepper */ +/** + * Ever wondered how to make a certain meal? Let's create a recipe list with JavaScript! + * + * Declare a variable that holds an empty object literal (your meal recipe). + * Give the object 3 properties: a title (string), a servings (number) and an ingredients (array of strings) property. + * Log each property out separately, using a loop (for, while or do/while) + * + * Expected result: + * + * Meal name: Omelette + * Serves: 2 + * Ingredients: 4 eggs, 2 strips of bacon, 1 tsp salt/pepper + */ + +const mealRecipe = { + title: 'Shakshuka', + servings: 2, + ingredients: [ + '4 eggs ', + ' 4 tomato ', + ' 1 tsp salt/pepper ', + ' 1 green pepper', + ], +}; + +for (const item in mealRecipe) { + if (item === 'title') { + console.log(`Meal name: ${mealRecipe[item]}`); + } else if (item === 'servings') { + console.log(`Serves: ${mealRecipe[item]}`); + } else { + const ingredientList = mealRecipe[item]; + console.log(`Ingredients: ${ingredientList.join(' ')}`); + } +} From 61b93b06e6a1c9014715cfa1ba2040d55cacdb62 Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Wed, 19 Feb 2025 10:32:42 +0100 Subject: [PATCH 06/15] Solve forth question --- Week1/practice-exercises/4-reading-list.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Week1/practice-exercises/4-reading-list.js b/Week1/practice-exercises/4-reading-list.js index f535657..bb8dd49 100644 --- a/Week1/practice-exercises/4-reading-list.js +++ b/Week1/practice-exercises/4-reading-list.js @@ -1,6 +1,6 @@ /** * Keep track of which books you read and which books you want to read! - * + * * Follow the steps: * Declare a variable that holds an array of 3 objects, where each object describes a book and has properties for the title (string), author (string), and alreadyRead (boolean indicating if you read it yet). * Loop through the array of books. @@ -9,3 +9,18 @@ * If you haven't read it log a string like You still need to read "The Lord of the Rings" */ +const readingList = [ + { title: 'To Kill a Mockingbird', author: 'Harper Lee', alreadyRead: true }, + { title: '1984', author: 'George Orwell', alreadyRead: false }, + { title: 'Moby Dick', author: 'Herman Melville', alreadyRead: true }, +]; + +readingList.forEach((book) => { + console.log( + `${book.title} by ${book.author} , ${ + book.alreadyRead + ? `You already read ${book.title}` + : ` I still need to read ${book.title}` + } ` + ); +}); From b9f9c69078ea6cb7a98f39baafd5e5a13e702a2e Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Wed, 19 Feb 2025 10:33:31 +0100 Subject: [PATCH 07/15] Solve fifth question --- .../practice-exercises/5-who-wants-a-drink.js | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/Week1/practice-exercises/5-who-wants-a-drink.js b/Week1/practice-exercises/5-who-wants-a-drink.js index f37f02b..6651041 100644 --- a/Week1/practice-exercises/5-who-wants-a-drink.js +++ b/Week1/practice-exercises/5-who-wants-a-drink.js @@ -3,9 +3,30 @@ * * Declare a variable that holds an empty array, called drinkTray. * Create a loop that runs 5 times. On each iteration, push a drink into the drinkTray variable. The drinkTray can only hold at most two instances of the same drink type, for example it can only hold 2 colas, 2 lemonades, 2 waters. - * + * * Log to the console: "Hey guys, I brought a [INSERT VALUES FROM ARRAY]!" (For example: "Hey guys, I brought a cola, cola, lemonade, lemonade, water!") */ // There are 3 different types of drinks: -const drinkTypes = ['cola', 'lemonade', 'water']; \ No newline at end of file +const drinkTypes = ['cola', 'lemonade', 'water']; + +// This is one way of doing it, there are many more. It hopefully showcases a nice use case of the double for loop +// It could also have been written with a while loop that would be a little more efficient + +const drinkTray = []; + +const pushElement = () => { + const randomElement = + drinkTypes[Math.floor(Math.random() * drinkTypes.length)]; + const count = drinkTray.filter((a) => a === randomElement).length; + if (count === 2) { + pushElement(); + } else { + drinkTray.push(randomElement); + } +}; +for (let i = 0; i <= 4; i++) { + pushElement(); +} + +console.log(drinkTray); From 66110c89348138b29a25cbf2999e3c425296719e Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Wed, 19 Feb 2025 21:55:21 +0100 Subject: [PATCH 08/15] Solution traffic light --- Week2/prep-exercises/1-traffic-light/traffic-light.js | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/Week2/prep-exercises/1-traffic-light/traffic-light.js b/Week2/prep-exercises/1-traffic-light/traffic-light.js index f4a5c1a..4bf26f2 100644 --- a/Week2/prep-exercises/1-traffic-light/traffic-light.js +++ b/Week2/prep-exercises/1-traffic-light/traffic-light.js @@ -1,4 +1,4 @@ -"use strict"; +'use strict'; /** * The `trafficLight` object is now no longer a global variable. Instead, * it is defined in function `main()` and passed as a parameter to other @@ -9,6 +9,8 @@ function getCurrentState(trafficLight) { // TODO // Should return the current state (i.e. colour) of the `trafficLight` // object passed as a parameter. + const { stateIndex, possibleStates } = trafficLight; + return possibleStates[stateIndex]; } function getNextStateIndex(trafficLight) { @@ -17,6 +19,9 @@ function getNextStateIndex(trafficLight) { // - if the color is green, it will turn to orange // - if the color is orange, it will turn to red // - if the color is red, it will turn to green + let { stateIndex, possibleStates } = trafficLight; + const possibleStatesLength = possibleStates.length; + return stateIndex >= possibleStatesLength - 1 ? 0 : ++stateIndex; } // This function loops for the number of seconds specified by the `secs` @@ -33,13 +38,13 @@ function waitSync(secs) { function main() { const trafficLight = { - possibleStates: ["green", "orange", "red"], + possibleStates: ['green', 'orange', 'red'], stateIndex: 0, }; for (let cycle = 0; cycle < 6; cycle++) { const currentState = getCurrentState(trafficLight); - console.log(cycle, "The traffic light is now", currentState); + console.log(cycle, 'The traffic light is now', currentState); waitSync(1); // Wait a second before going to the next state trafficLight.stateIndex = getNextStateIndex(trafficLight); From 8f04123ae65b08c4ef602c9bf9d0e228d0022016 Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Wed, 19 Feb 2025 21:57:36 +0100 Subject: [PATCH 09/15] Solution experiments --- Week2/prep-exercises/2-experiments/index.js | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/Week2/prep-exercises/2-experiments/index.js b/Week2/prep-exercises/2-experiments/index.js index 7e5aa92..c6f3e88 100644 --- a/Week2/prep-exercises/2-experiments/index.js +++ b/Week2/prep-exercises/2-experiments/index.js @@ -1,6 +1,6 @@ -"use strict"; +'use strict'; -function runExperiment(sampleSize) { +function runExperiment(sampleSize = 100) { const valueCounts = [0, 0, 0, 0, 0, 0]; // TODO @@ -8,11 +8,15 @@ function runExperiment(sampleSize) { // In each loop iteration: // // 1. Generate a random integer between 1 and 6 (as if throwing a six-sided die). + // 2. Add `1` to the element of the `valueCount` that corresponds to the random // value from the previous step. Use the first element of `valueCounts` // for keeping a count how many times the value 1 is thrown, the second // element for value 2, etc. - + for (let i = 1; i <= sampleSize; i++) { + const randomNumber = Math.floor(Math.random() * 6); + ++valueCounts[randomNumber]; + } const results = []; // TODO @@ -25,12 +29,19 @@ function runExperiment(sampleSize) { // two decimals, e.g. '14.60'. // 3. Then push that string onto the `results` array. + for (const count of valueCounts) { + results.push(((count / sampleSize) * 100).toFixed(2)); + } return results; } function main() { const sampleSizes = [100, 1000, 1000000]; + for (const size of sampleSizes) { + const result = runExperiment(size); + console.log(result, size); + } // TODO // Write a for..of loop that calls the `runExperiment()` function for each // value of the `sampleSizes` array. From b2df6138b6e2bc448160bc42c4cd894b9a943110 Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Tue, 25 Feb 2025 14:34:35 +0100 Subject: [PATCH 10/15] Removed comments from week 2 --- .../1-traffic-light/traffic-light.js | 13 ---------- Week2/prep-exercises/2-experiments/index.js | 26 +------------------ 2 files changed, 1 insertion(+), 38 deletions(-) diff --git a/Week2/prep-exercises/1-traffic-light/traffic-light.js b/Week2/prep-exercises/1-traffic-light/traffic-light.js index 4bf26f2..becce14 100644 --- a/Week2/prep-exercises/1-traffic-light/traffic-light.js +++ b/Week2/prep-exercises/1-traffic-light/traffic-light.js @@ -6,29 +6,16 @@ */ function getCurrentState(trafficLight) { - // TODO - // Should return the current state (i.e. colour) of the `trafficLight` - // object passed as a parameter. const { stateIndex, possibleStates } = trafficLight; return possibleStates[stateIndex]; } function getNextStateIndex(trafficLight) { - // TODO - // Return the index of the next state of the `trafficLight` such that: - // - if the color is green, it will turn to orange - // - if the color is orange, it will turn to red - // - if the color is red, it will turn to green let { stateIndex, possibleStates } = trafficLight; const possibleStatesLength = possibleStates.length; return stateIndex >= possibleStatesLength - 1 ? 0 : ++stateIndex; } -// This function loops for the number of seconds specified by the `secs` -// parameter and then returns. -// IMPORTANT: This is not the recommended way to implement 'waiting' in -// JavaScript. You will learn better ways of doing this when you learn about -// asynchronous code. function waitSync(secs) { const start = Date.now(); while (Date.now() - start < secs * 1000) { diff --git a/Week2/prep-exercises/2-experiments/index.js b/Week2/prep-exercises/2-experiments/index.js index c6f3e88..8458a2f 100644 --- a/Week2/prep-exercises/2-experiments/index.js +++ b/Week2/prep-exercises/2-experiments/index.js @@ -3,32 +3,12 @@ function runExperiment(sampleSize = 100) { const valueCounts = [0, 0, 0, 0, 0, 0]; - // TODO - // Write a for loop that iterates `sampleSize` times (sampleSize is a number). - // In each loop iteration: - // - // 1. Generate a random integer between 1 and 6 (as if throwing a six-sided die). - - // 2. Add `1` to the element of the `valueCount` that corresponds to the random - // value from the previous step. Use the first element of `valueCounts` - // for keeping a count how many times the value 1 is thrown, the second - // element for value 2, etc. for (let i = 1; i <= sampleSize; i++) { const randomNumber = Math.floor(Math.random() * 6); ++valueCounts[randomNumber]; } const results = []; - // TODO - // Write a for..of loop for the `valueCounts` array created in the previous - // loop. In each loop iteration: - // 1. For each possible value of the die (1-6), compute the percentage of how - // many times that value was thrown. Remember that the first value of - // `valueCounts` represent the die value of 1, etc. - // 2. Convert the computed percentage to a number string with a precision of - // two decimals, e.g. '14.60'. - // 3. Then push that string onto the `results` array. - for (const count of valueCounts) { results.push(((count / sampleSize) * 100).toFixed(2)); } @@ -42,11 +22,7 @@ function main() { const result = runExperiment(size); console.log(result, size); } - // TODO - // Write a for..of loop that calls the `runExperiment()` function for each - // value of the `sampleSizes` array. - // Log the results of each experiment as well as the experiment size to the - // console. + // The expected output could look like this: // // [ '26.00', '17.00', '10.00', '19.00', '16.00', '12.00' ] 100 From 7adebbf55450246eb3ce6d99e02266b1ca45fbf0 Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Tue, 25 Feb 2025 18:17:49 +0100 Subject: [PATCH 11/15] Solved challenges week 3 --- Week3/challenges/1-sum-entries.js | 18 +++++++--- Week3/challenges/2-sum-three-entries.js | 21 +++++++++--- Week3/challenges/3-password-validation.js | 33 +++++++++++++----- Week3/challenges/4-bank-account.js | 41 +++++++++++++++++++---- 4 files changed, 88 insertions(+), 25 deletions(-) diff --git a/Week3/challenges/1-sum-entries.js b/Week3/challenges/1-sum-entries.js index f7dd419..62462fb 100644 --- a/Week3/challenges/1-sum-entries.js +++ b/Week3/challenges/1-sum-entries.js @@ -6,12 +6,22 @@ In the list below you have an array of numbers. The goal is to find the two numb Once you have found those numbers, multiply the numbers and store the result of that in the result variable. */ - const list = [1721, 979, 366, 299, 675, 1456]; let result; - -// Write your code here +const calculatResult = () => { + for (let i = 0; i < list.length; i++) { + for (let j = i + 1; j < list.length; j++) { + if (list[i] + list[j] === 2020) { + return list[i] * list[j]; + } + } + } +}; +result = calculatResult(); // TEST CODE, do not change -console.assert(result === 514579, `The result is not correct, it is ${result}, but should be 514579`); \ No newline at end of file +console.assert( + result === 514579, + `The result is not correct, it is ${result}, but should be 514579` +); diff --git a/Week3/challenges/2-sum-three-entries.js b/Week3/challenges/2-sum-three-entries.js index f5f8773..8ad5f95 100644 --- a/Week3/challenges/2-sum-three-entries.js +++ b/Week3/challenges/2-sum-three-entries.js @@ -6,12 +6,23 @@ In the list below you have an array of numbers. The goal is to find the three nu Once you have found those numbers, multiply the numbers and store the result of that in the result variable. */ - const list = [1721, 979, 366, 299, 675, 1456]; let result; - -// Write your code here - +const calculatResult = () => { + for (let i = 0; i < list.length; i++) { + for (let j = i + 1; j < list.length; j++) { + for (let k = j + 1; k < list.length; k++) { + if (list[i] + list[j] + list[k] === 2020) { + return list[i] * list[j] * list[k]; // we need to end the function when we find the elements + } + } + } + } +}; +result = calculatResult(); // TEST CODE, do not change -console.assert(result === 241861950, `The result is not correct, it is ${result}, but should be 241861950`); \ No newline at end of file +console.assert( + result === 241861950, + `The result is not correct, it is ${result}, but should be 241861950` +); diff --git a/Week3/challenges/3-password-validation.js b/Week3/challenges/3-password-validation.js index fa7ad11..6157576 100644 --- a/Week3/challenges/3-password-validation.js +++ b/Week3/challenges/3-password-validation.js @@ -1,23 +1,38 @@ - /** * Credit to https://adventofcode.com/ for this exercise - * + * * Each object in the passwordList gives a password policy and then the password. * The times field says the minimal and maximal amount of times the letter should be in the password. So 1-3 means at least 1 time, at most 3 times. * The letter field gives which letter should be counted * The password field gives the password - * + * * In the list 2 passwords are valid, the middle one is not as there is no b in the password. - * + * * We expect the output: - * + * * 'abcde' is VALID, a is present 1 times and should have been present at least 1 and at most 3 times * 'cdefg' is INVALID, b is present 0 times and should have been present at least 1 and at most 3 times * 'ccccccccc' is VALID, c is present 9 times and should have been present at least 2 and at most 9 times */ const passwordList = [ - { times: '1-3', letter: 'a', password: 'abcde'}, - { times: '1-3', letter: 'b', password: 'cdefg'}, - { times: '2-9', letter: 'c', password: 'ccccccccc'} -]; \ No newline at end of file + { times: '1-3', letter: 'a', password: 'abcde' }, + { times: '1-3', letter: 'b', password: 'cdefg' }, + { times: '2-9', letter: 'c', password: 'ccccccccc' }, +]; + +const isValid = ({ times, letter, password }) => { + const timesArr = times.split('-').map((element) => +element); + const passwordArr = [...password]; + const letterCount = passwordArr.filter((char) => char === letter).length; + + if (letterCount >= timesArr[0] && letterCount <= timesArr[1]) { + return `${password} is VALID, ${letter} is present ${letterCount} times and should have been present at least ${timesArr[0]} and at most ${timesArr[1]} times`; + } else { + return `${password} is INVALID, ${letter} is present ${letterCount} times and should have been present at least ${timesArr[0]} and at most ${timesArr[1]} times`; + } +}; + +passwordList.forEach((password) => { + console.log(isValid(password)); +}); diff --git a/Week3/challenges/4-bank-account.js b/Week3/challenges/4-bank-account.js index 8f0f035..66985f6 100644 --- a/Week3/challenges/4-bank-account.js +++ b/Week3/challenges/4-bank-account.js @@ -22,16 +22,43 @@ const bankAccount = { { prevAmount: 350, newAmount: 250, - reason: "Donation", + reason: 'Donation', }, ], }; +const payExpense = (amount, expenseReason) => { + const { currentBalance, transactions } = bankAccount; + if (currentBalance >= amount) { + bankAccount.currentBalance = currentBalance - amount; + bankAccount.transactions = [ + ...transactions, + { + prevAmount: currentBalance, + newAmount: currentBalance - amount, + reason: expenseReason, + }, + ]; + return true; + } else { + return false; + } +}; const donateMoney = (amount, onSuccess, onFail) => { - // TODO complete this function + const successfulPayment = payExpense(amount, 'Donation'); + if (successfulPayment) { + onSuccess(); + } else { + onFail(); + } }; const payRent = (amount, onSuccess, onFail) => { - // TODO complete this function + const successfulPayment = payExpense(amount, 'Rent'); + if (successfulPayment) { + onSuccess(); + } else { + onFail(); + } }; /** @@ -39,17 +66,17 @@ const payRent = (amount, onSuccess, onFail) => { */ const onSuccessEnglish = () => { - console.log("Payment successful! Thank you!"); + console.log('Payment successful! Thank you!'); }; const onFailEnglish = () => { - console.log("You do not have enough money to make this payment."); + console.log('You do not have enough money to make this payment.'); }; const onSuccessDutch = () => { - console.log("Betaling geslaagd! Dank u!"); + console.log('Betaling geslaagd! Dank u!'); }; const onFailDutch = () => { - console.log("U heeft niet voldoende saldo om deze betaling te doen."); + console.log('U heeft niet voldoende saldo om deze betaling te doen.'); }; donateMoney(100, onSuccessEnglish, onFailEnglish); From d8e5d44bfd9c8b8191ef3e0920ef30fb4359fa4f Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Tue, 25 Feb 2025 20:24:44 +0100 Subject: [PATCH 12/15] Solved prep questions --- .../1-hyf-program/1-find-mentors.js | 21 ++++++++++--- .../1-hyf-program/2-class-list.js | 31 ++++++++++++++++--- 2 files changed, 42 insertions(+), 10 deletions(-) diff --git a/Week3/prep-exercises/1-hyf-program/1-find-mentors.js b/Week3/prep-exercises/1-hyf-program/1-find-mentors.js index 72baa61..4afeec5 100644 --- a/Week3/prep-exercises/1-hyf-program/1-find-mentors.js +++ b/Week3/prep-exercises/1-hyf-program/1-find-mentors.js @@ -1,4 +1,4 @@ -import { modules, students, mentors, classes } from "./hyf.js"; +import { modules, students, mentors, classes } from './hyf.js'; /** * Tjebbe would like help to get a list of possible mentors for a module. @@ -8,10 +8,15 @@ import { modules, students, mentors, classes } from "./hyf.js"; * ['John', 'Mary'] */ const possibleMentorsForModule = (moduleName) => { - // TODO complete this function + const availableMentors = mentors + .filter(({ canTeach }) => canTeach.includes(moduleName)) + .map(({ name }) => name); + return availableMentors; }; // You can uncomment out this line to try your function -// console.log(possibleMentorsForModule('using-apis')); + +console.log(possibleMentorsForModule('using-apis')); +console.log(possibleMentorsForModule('javascript')); /** * Tjebbe wants to make it even easier for himself. @@ -20,7 +25,13 @@ const possibleMentorsForModule = (moduleName) => { * It should return a single name. */ const findMentorForModule = (moduleName) => { - // TODO complete this function + const availableMentors = possibleMentorsForModule(moduleName); + if (availableMentors.length >= 0) { + const randomNumber = Math.floor(Math.random() * availableMentors.length); + return availableMentors[randomNumber]; + } else { + console.log('No available mentor for this module'); + } }; // You can uncomment out this line to try your function -// console.log(findMentorForModule('javascript')); +console.log(findMentorForModule('javascript')); diff --git a/Week3/prep-exercises/1-hyf-program/2-class-list.js b/Week3/prep-exercises/1-hyf-program/2-class-list.js index 44d2798..26fbbdf 100644 --- a/Week3/prep-exercises/1-hyf-program/2-class-list.js +++ b/Week3/prep-exercises/1-hyf-program/2-class-list.js @@ -1,4 +1,4 @@ -import { modules, students, mentors, classes } from "./hyf.js"; +import { modules, students, mentors, classes } from './hyf.js'; /** * We would like to have a list of everyone that is currently participating in a class. @@ -12,10 +12,24 @@ import { modules, students, mentors, classes } from "./hyf.js"; * [{ name: 'John', role: 'student' }, { name: 'Mary', role: 'mentor' }] */ const getPeopleOfClass = (className) => { - // TODO complete this function + const { currentModule } = classes.find((item) => item.name === className); + + const studentsClass = students + .filter((student) => student.class === className) + .map((student) => { + return { name: student.name, role: 'student' }; + }); + + const mentorsClass = mentors + .filter((mentor) => mentor.nowTeaching === currentModule) + .map((mentor) => { + return { name: mentor.name, role: 'mentor' }; + }); + + return [...studentsClass, ...mentorsClass]; }; // You can uncomment out this line to try your function -// console.log(getPeopleOfClass('class34')); +console.log(getPeopleOfClass('class34')); /** * We would like to have a complete overview of the current active classes. @@ -30,7 +44,14 @@ const getPeopleOfClass = (className) => { * } */ const getActiveClasses = () => { - // TODO complete this function + const activeClasses = classes.filter((specificClass) => specificClass.active); + + return activeClasses.reduce((accumulator, activeClass) => { + return { + ...accumulator, + [activeClass.name]: getPeopleOfClass(activeClass.name), + }; + }, {}); }; // You can uncomment out this line to try your function -// console.log(getActiveClasses()); +console.log(getActiveClasses()); From 1b87c7d1aff3d34fae668258e6b92c82acb5df5c Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Fri, 7 Mar 2025 01:36:49 +0100 Subject: [PATCH 13/15] solved prep exercise wallet --- Week4/prep-exercises/1-wallet/ex2-classes.js | 27 +++++++++++++++++-- Week4/prep-exercises/1-wallet/ex3-object.js | 24 ++++++++++++++++- .../1-wallet/ex4-object-shared-methods.js | 16 ++++++++++- .../prep-exercises/1-wallet/ex5-prototype.js | 15 ++++++++++- 4 files changed, 77 insertions(+), 5 deletions(-) diff --git a/Week4/prep-exercises/1-wallet/ex2-classes.js b/Week4/prep-exercises/1-wallet/ex2-classes.js index f016137..fa6fbf7 100644 --- a/Week4/prep-exercises/1-wallet/ex2-classes.js +++ b/Week4/prep-exercises/1-wallet/ex2-classes.js @@ -3,10 +3,14 @@ import eurosFormatter from './euroFormatter.js'; class Wallet { #name; #cash; + #dayTotalWithdrawals; + #dailyAllowance; constructor(name, cash) { this.#name = name; this.#cash = cash; + this.#dailyAllowance = 40; + this.#dayTotalWithdrawals = 0; } get name() { @@ -22,8 +26,13 @@ class Wallet { console.log(`Insufficient funds!`); return 0; } + if (this.#dayTotalWithdrawals + amount > this.#dailyAllowance) { + console.log(`Insufficient remaining daily allowance!`); + return 0; + } this.#cash -= amount; + this.#dayTotalWithdrawals += amount; return amount; } @@ -34,12 +43,25 @@ class Wallet { }` ); const withdrawnAmount = this.withdraw(amount); - wallet.deposit(withdrawnAmount); + if (withdrawnAmount > 0) { + wallet.deposit(withdrawnAmount); + } + } + + setDailyAllowance(newAllowance) { + this.#dailyAllowance = newAllowance; + console.log( + `Daily allowance set to: ${eurosFormatter.format(newAllowance)}` + ); + } + + resetDailyAllowance() { + this.#dayTotalWithdrawals = 0; } reportBalance() { console.log( - `Name: ${this.name}, balance: ${eurosFormatter.format(this.#cash)}` + `Name: ${this.#name}, balance: ${eurosFormatter.format(this.#cash)}` ); } } @@ -50,6 +72,7 @@ function main() { const walletJane = new Wallet('Jane', 20); walletJack.transferInto(walletJoe, 50); + walletJack.setDailyAllowance(80); walletJane.transferInto(walletJoe, 25); walletJane.deposit(20); diff --git a/Week4/prep-exercises/1-wallet/ex3-object.js b/Week4/prep-exercises/1-wallet/ex3-object.js index e94faac..42c09e6 100644 --- a/Week4/prep-exercises/1-wallet/ex3-object.js +++ b/Week4/prep-exercises/1-wallet/ex3-object.js @@ -4,6 +4,8 @@ function createWallet(name, cash = 0) { return { _name: name, _cash: cash, + _dailyAllowance: 40, + _dayTotalWithdrawals: 0, deposit: function (amount) { this._cash += amount; @@ -15,7 +17,13 @@ function createWallet(name, cash = 0) { return 0; } + if (this._dayTotalWithdrawals + amount > this._dailyAllowance) { + console.log(`Insufficient remaining daily allowance!`); + return 0; + } + this._cash -= amount; + this._dayTotalWithdrawals += amount; return amount; }, @@ -26,7 +34,9 @@ function createWallet(name, cash = 0) { } to ${wallet.getName()}` ); const withdrawnAmount = this.withdraw(amount); - wallet.deposit(withdrawnAmount); + if (withdrawnAmount > 0) { + wallet.deposit(withdrawnAmount); + } }, reportBalance: function () { @@ -38,6 +48,17 @@ function createWallet(name, cash = 0) { getName: function () { return this._name; }, + + resetDailyAllowance: function () { + this._dayTotalWithdrawals = 0; + }, + + setDailyAllowance: function (newAllowance) { + this._dailyAllowance = newAllowance; + console.log( + `Daily allowance set to: ${eurosFormatter.format(newAllowance)}` + ); + }, }; } @@ -47,6 +68,7 @@ function main() { const walletJane = createWallet('Jane', 20); walletJack.transferInto(walletJoe, 50); + walletJack.setDailyAllowance(80); walletJane.transferInto(walletJoe, 25); walletJane.deposit(20); diff --git a/Week4/prep-exercises/1-wallet/ex4-object-shared-methods.js b/Week4/prep-exercises/1-wallet/ex4-object-shared-methods.js index bd4fd20..8bafbec 100644 --- a/Week4/prep-exercises/1-wallet/ex4-object-shared-methods.js +++ b/Week4/prep-exercises/1-wallet/ex4-object-shared-methods.js @@ -21,7 +21,9 @@ function transferInto(wallet, amount) { } to ${wallet.getName()}` ); const withdrawnAmount = this.withdraw(amount); - wallet.deposit(withdrawnAmount); + if (withdrawnAmount > 0) { + wallet.deposit(withdrawnAmount); + } } function reportBalance() { @@ -29,6 +31,13 @@ function reportBalance() { `Name: ${this._name}, balance: ${eurosFormatter.format(this._cash)}` ); } +function setDailyAllowance(newAllowance) { + this._dailyAllowance = newAllowance; + console.log(`Daily allowance set to: ${eurosFormatter.format(newAllowance)}`); +} +function resetDailyAllowance() { + this._dayTotalWithdrawals = 0; +} function getName() { return this._name; @@ -38,11 +47,15 @@ function createWallet(name, cash = 0) { return { _name: name, _cash: cash, + _dailyAllowance: 40, + _dayTotalWithdrawals: 0, deposit, withdraw, transferInto, reportBalance, getName, + setDailyAllowance, + resetDailyAllowance, }; } @@ -52,6 +65,7 @@ function main() { const walletJane = createWallet('Jane', 20); walletJack.transferInto(walletJoe, 50); + walletJack.setDailyAllowance(80); walletJane.transferInto(walletJoe, 25); walletJane.deposit(20); diff --git a/Week4/prep-exercises/1-wallet/ex5-prototype.js b/Week4/prep-exercises/1-wallet/ex5-prototype.js index 7cba410..204deff 100644 --- a/Week4/prep-exercises/1-wallet/ex5-prototype.js +++ b/Week4/prep-exercises/1-wallet/ex5-prototype.js @@ -3,6 +3,8 @@ import eurosFormatter from './euroFormatter.js'; function Wallet(name, cash) { this._name = name; this._cash = cash; + this._dailyAllowance = 40; + this._dayTotalWithdrawals = 0; } Wallet.prototype.deposit = function (amount) { @@ -26,7 +28,9 @@ Wallet.prototype.transferInto = function (wallet, amount) { } to ${wallet.getName()}` ); const withdrawnAmount = this.withdraw(amount); - wallet.deposit(withdrawnAmount); + if (withdrawnAmount > 0) { + wallet.deposit(withdrawnAmount); + } }; Wallet.prototype.reportBalance = function () { @@ -35,6 +39,14 @@ Wallet.prototype.reportBalance = function () { ); }; +Wallet.prototype.setDailyAllowance = function (newAllowance) { + this._dailyAllowance = newAllowance; + console.log(`Daily allowance set to: ${eurosFormatter.format(newAllowance)}`); +}; + +Wallet.prototype.resetDailyAllowance = function () { + this._dayTotalWithdrawals = 0; +}; Wallet.prototype.getName = function () { return this._name; }; @@ -45,6 +57,7 @@ function main() { const walletJane = new Wallet('Jane', 20); walletJack.transferInto(walletJoe, 50); + walletJack.setDailyAllowance(80); walletJane.transferInto(walletJoe, 25); walletJane.deposit(20); From c76256003567966a26f3d0832ee3ea5a79d8e3a4 Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Fri, 7 Mar 2025 02:52:22 +0100 Subject: [PATCH 14/15] Solved game of life question --- Week4/prep-exercises/2-game-of-life/Cell.js | 25 ++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/Week4/prep-exercises/2-game-of-life/Cell.js b/Week4/prep-exercises/2-game-of-life/Cell.js index cac08da..d3f677c 100644 --- a/Week4/prep-exercises/2-game-of-life/Cell.js +++ b/Week4/prep-exercises/2-game-of-life/Cell.js @@ -14,6 +14,7 @@ export default class Cell { this.y = y; this.alive = Math.random() > 0.5; this.nextAlive = false; + this.lifeTime = this.alive ? 1 : 0; } draw(context) { @@ -28,7 +29,18 @@ export default class Cell { if (this.alive) { // Draw living this inside background - context.fillStyle = `rgb(24, 215, 236)`; + let opacity = 0; + if (this.lifeTime === 1) { + opacity = 0.25; + } else if (this.lifeTime === 2) { + opacity = 0.5; + } else if (this.lifeTime === 3) { + opacity = 0.75; + } else if (this.lifeTime >= 4) { + opacity = 1; + } + + context.fillStyle = `rgba(24, 215, 236,${opacity})`; context.fillRect( this.x * Cell.size + 1, this.y * Cell.size + 1, @@ -42,12 +54,23 @@ export default class Cell { if (aliveNeighbors === 2) { // Living cell remains living, dead cell remains dead this.nextAlive = this.alive; + if (this.alive) { + this.lifeTime++; + } else { + this.lifeTime = 0; + } } else if (aliveNeighbors === 3) { // Dead cell becomes living, living cell remains living + if (!this.alive) { + this.lifeTime = 1; + } else { + this.lifeTime++; + } this.nextAlive = true; } else { // Living cell dies, dead cell remains dead this.nextAlive = false; + this.lifeTime = 0; } } From 921994b4f6b4cfb7f771161496cbf42ce3fd5ebe Mon Sep 17 00:00:00 2001 From: Salma Issa Date: Fri, 14 Mar 2025 13:49:46 +0100 Subject: [PATCH 15/15] fix game of life solution --- Week4/prep-exercises/2-game-of-life/Cell.js | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/Week4/prep-exercises/2-game-of-life/Cell.js b/Week4/prep-exercises/2-game-of-life/Cell.js index d3f677c..a187748 100644 --- a/Week4/prep-exercises/2-game-of-life/Cell.js +++ b/Week4/prep-exercises/2-game-of-life/Cell.js @@ -29,6 +29,7 @@ export default class Cell { if (this.alive) { // Draw living this inside background + // let opacity1 = Math.min(0.25 * this.lifeTime, 1); let opacity = 0; if (this.lifeTime === 1) { opacity = 0.25; @@ -54,19 +55,11 @@ export default class Cell { if (aliveNeighbors === 2) { // Living cell remains living, dead cell remains dead this.nextAlive = this.alive; - if (this.alive) { - this.lifeTime++; - } else { - this.lifeTime = 0; - } + + this.lifeTime++; } else if (aliveNeighbors === 3) { - // Dead cell becomes living, living cell remains living - if (!this.alive) { - this.lifeTime = 1; - } else { - this.lifeTime++; - } this.nextAlive = true; + this.lifeTime++; } else { // Living cell dies, dead cell remains dead this.nextAlive = false;