diff --git a/Week1/practice-exercises/1-remove-the-comma.js b/Week1/practice-exercises/1-remove-the-comma.js index b71cffd..ebcbab7 100644 --- a/Week1/practice-exercises/1-remove-the-comma.js +++ b/Week1/practice-exercises/1-remove-the-comma.js @@ -6,9 +6,10 @@ */ let myString = 'hello,this,is,a,difficult,to,read,sentence'; +console.log(myString.replaceAll(",", " ")); /* --- 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'); diff --git a/Week1/practice-exercises/2-even-odd-reporter.js b/Week1/practice-exercises/2-even-odd-reporter.js index 6edf23e..ccb40da 100644 --- a/Week1/practice-exercises/2-even-odd-reporter.js +++ b/Week1/practice-exercises/2-even-odd-reporter.js @@ -7,3 +7,15 @@ * If it's even, log to the console The number [PUT_NUMBER_HERE] is even!. */ +for (let i = 0; i < 21; i++){ + if (i%2 === 0) { + console.log("The number", i, "is even!"); + } + else { + console.log("The number", i, "is odd!"); + } +} + + + + diff --git a/Week1/practice-exercises/3-recipe-card.js b/Week1/practice-exercises/3-recipe-card.js index 24bcb54..eee7544 100644 --- a/Week1/practice-exercises/3-recipe-card.js +++ b/Week1/practice-exercises/3-recipe-card.js @@ -12,3 +12,19 @@ * Ingredients: 4 eggs, 2 strips of bacon, 1 tsp salt/pepper */ +const mealRecipe = { + title: "Omelette", + servings: 2, + ingridients: ["4 eggs", "2 strips of bacon", "1 tsp salt/pepper"] +}; +for (let property in mealRecipe) { + if (property == 'title') { + console.log(`Meal name: ${mealRecipe[property]}`); + } else if (property == 'servings') { + console.log(`Serves: ${mealRecipe[property]}`); + } else { + const ingredientList = mealRecipe[property]; + + console.log(`Ingedients: ${ingredientList.join(', ')}`); + } +} diff --git a/Week1/practice-exercises/4-reading-list.js b/Week1/practice-exercises/4-reading-list.js index f535657..621ba08 100644 --- a/Week1/practice-exercises/4-reading-list.js +++ b/Week1/practice-exercises/4-reading-list.js @@ -9,3 +9,20 @@ * If you haven't read it log a string like You still need to read "The Lord of the Rings" */ +const books = [ + {title: "The Lord of the Rings", author: "J.R.R. Tolkien", isRead: true}, + {title: "The Hobbit", author: "J.R.R. Tolkien", isRead: true}, + {title: "Airport", author: "Arthur Hailey", isRead: false} +]; + +books.forEach(book => { + let bookDetails = `"${book.title}" by ${book.author}`; + + if (book.isRead) { + console.log(`${bookDetails}. You already read "${book.title}".`); + } + else { + console.log(`${bookDetails}. You still need to read "${book.title}".`); + } +} +); \ No newline at end of file diff --git a/Week1/practice-exercises/5-who-wants-a-drink.js b/Week1/practice-exercises/5-who-wants-a-drink.js index f37f02b..c847962 100644 --- a/Week1/practice-exercises/5-who-wants-a-drink.js +++ b/Week1/practice-exercises/5-who-wants-a-drink.js @@ -8,4 +8,14 @@ */ // There are 3 different types of drinks: -const drinkTypes = ['cola', 'lemonade', 'water']; \ No newline at end of file +const drinkTypes = ['cola', 'lemonade', 'water']; +let drinkTray = []; +for (let i = 0; i < 5; i++) { + let item = drinkTypes[Math.floor(Math.random()*drinkTypes.length)]; + drinkTray.push(item); + if (drinkTray.filter(x => x==item).length > 2) { + drinkTray.pop(); + i--; + } +} +console.log(`Hey guys, I brought a ${drinkTray.join(", ")}!`); \ No newline at end of file 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..4d5ebda 100644 --- a/Week1/prep-exercises/1-traffic-light/traffic-light-1.js +++ b/Week1/prep-exercises/1-traffic-light/traffic-light-1.js @@ -1,21 +1,31 @@ "use strict"; /** - * The `state` property says what the traffic light's state (i.e. colour) is at + * The `state` property says what the traffic light's state (i.e. color) 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); + const currentState = trafficLight.state; + console.log("The traffic light is on", currentState); - // TODO - // if the color is green, turn it orange - // if the color is orange, turn it red - // if the color is red, add 1 to rotations and turn it green + // TODO + // if the color is green, turn it orange + if (currentState === "green") { + trafficLight.state = "orange"; + } + // if the color is orange, turn it red + else if (currentState === "orange") { + trafficLight.state = "red"; + } + // if the color is red, add 1 to rotations and turn it green + else { + trafficLight.state = "green"; + rotations++; + } } /** 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..e2c6707 100644 --- a/Week1/prep-exercises/1-traffic-light/traffic-light-2.js +++ b/Week1/prep-exercises/1-traffic-light/traffic-light-2.js @@ -4,6 +4,7 @@ * in which the traffic light can be. * The `stateIndex` property indicates which of the possible states is current. */ + const trafficLight = { possibleStates: ["green", "orange", "red"], stateIndex: 0, @@ -16,10 +17,19 @@ while (cycle < 2) { // TODO // if the color is green, turn it orange + if (currentState === "green") { + trafficLight.stateIndex = 1; + } // if the color is orange, turn it red - // if the color is red, add 1 to cycles and turn it green + else if (currentState === "orange") { + trafficLight.stateIndex = 2; +} + // if the color is red, add 1 to rotations and turn it green + else { + trafficLight.stateIndex = 0; + cycle++; +} } - /** * The output should be: diff --git a/Week2/prep-exercises/1-traffic-light/traffic-light.js b/Week2/prep-exercises/1-traffic-light/traffic-light.js index f4a5c1a..871a9fd 100644 --- a/Week2/prep-exercises/1-traffic-light/traffic-light.js +++ b/Week2/prep-exercises/1-traffic-light/traffic-light.js @@ -6,44 +6,56 @@ */ function getCurrentState(trafficLight) { - // TODO - // Should return the current state (i.e. colour) of the `trafficLight` - // object passed as a parameter. + // TODO + // Should return the current state (i.e. color) of the `trafficLight` + // object passed as a parameter. + return trafficLight.possibleStates[trafficLight.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 + // TODO + // Return the index of the next state of the `trafficLight` such that: + + // if the color is green, turn it orange + if (trafficLight.stateIndex === 0) { + return 1; + } + // if the color is orange, turn it red + else if (trafficLight.stateIndex === 1) { + return 2; + } + // if the color is red, add 1 to rotations and turn it green + else { + return 0; + } } + // 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) { - // nothing do to here - } + const start = Date.now(); + while (Date.now() - start < secs * 1000) { + // nothing do to here + } } function main() { - const trafficLight = { - 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); - - waitSync(1); // Wait a second before going to the next state - trafficLight.stateIndex = getNextStateIndex(trafficLight); - } + const trafficLight = { + 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); + + waitSync(1); // Wait a second before going to the next state + trafficLight.stateIndex = getNextStateIndex(trafficLight); + } } main(); diff --git a/Week2/prep-exercises/2-experiments/index.js b/Week2/prep-exercises/2-experiments/index.js index 7e5aa92..b2da15f 100644 --- a/Week2/prep-exercises/2-experiments/index.js +++ b/Week2/prep-exercises/2-experiments/index.js @@ -1,46 +1,61 @@ "use strict"; function runExperiment(sampleSize) { - 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. - - 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. - - return results; + 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 = 0; i < sampleSize; i++) { + const randomInteger = Math.floor(Math.random()*6)+1; + valueCounts[randomInteger - 1] += 1; + } + 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. + let j = 0; + for (const value of valueCounts) { + results[j] = (value/sampleSize * 100).toFixed(2); + j++; + + } + + return results; } function main() { - const sampleSizes = [100, 1000, 1000000]; - - // 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 - // [ '14.60', '17.10', '19.30', '15.50', '16.70', '16.80' ] 1000 - // [ '16.71', '16.68', '16.69', '16.66', '16.67', '16.59' ] 1000000 + const sampleSizes = [100, 1000, 1000000]; + + // 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 + // [ '14.60', '17.10', '19.30', '15.50', '16.70', '16.80' ] 1000 + // [ '16.71', '16.68', '16.69', '16.66', '16.67', '16.59' ] 1000000 + + for (const sampleSize of sampleSizes) { + const experimentResult = runExperiment(sampleSize); + console.log(experimentResult, sampleSize); + } } main(); diff --git a/Week2/prep-exercises/README.md b/Week2/prep-exercises/README.md new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Week2/prep-exercises/README.md @@ -0,0 +1 @@ + diff --git a/Week3/challenges/1-sum-entries.js b/Week3/challenges/1-sum-entries.js index f7dd419..57f73a2 100644 --- a/Week3/challenges/1-sum-entries.js +++ b/Week3/challenges/1-sum-entries.js @@ -9,9 +9,13 @@ Once you have found those numbers, multiply the numbers and store the result of const list = [1721, 979, 366, 299, 675, 1456]; let result; - -// Write your code here +list.forEach((num1, index1) => { + const num2 = list.find((num, index2) => index2 > index1 && num1 + num === 2020); + if (num2) { + result = num1 * num2; + } +}); // 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 diff --git a/Week3/challenges/2-sum-three-entries.js b/Week3/challenges/2-sum-three-entries.js index f5f8773..c38642a 100644 --- a/Week3/challenges/2-sum-three-entries.js +++ b/Week3/challenges/2-sum-three-entries.js @@ -10,8 +10,12 @@ Once you have found those numbers, multiply the numbers and store the result of const list = [1721, 979, 366, 299, 675, 1456]; let result; -// Write your code here - - +list.forEach((num1, index1) => { + list.forEach((num2, index2) => { + const num3 = list.find((num, index3) => index3 !== index1 && index3 !== index2 && index2 !== index1 && num1 + num2 + num === 2020); + if (num3) { + result = num1 * num2 * num3; + }}) +}); // 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 diff --git a/Week3/challenges/3-password-validation.js b/Week3/challenges/3-password-validation.js index fa7ad11..df8ae96 100644 --- a/Week3/challenges/3-password-validation.js +++ b/Week3/challenges/3-password-validation.js @@ -1,23 +1,37 @@ - /** * 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" }, +]; + +passwordList.forEach((item) => { + const { password, times, letter } = item; + const timesArray = times.split("-"); + const passLen = Array.from(password).filter(character => character === letter).length; + if (passLen >= timesArray[0] && passLen <= timesArray[1]) { + console.log( + `${password} is VALID, ${letter} is present ${passLen} times and should have been present at least ${timesArray[0]} and at most ${timesArray[1]} times` + ); + } else { + console.log( + `${password} is INVALID, ${letter} is present ${passLen} times and should have been present at least ${timesArray[0]} and at most ${timesArray[1]} times` + ); + } +}); diff --git a/Week3/challenges/4-bank-account.js b/Week3/challenges/4-bank-account.js index 8f0f035..0572ee4 100644 --- a/Week3/challenges/4-bank-account.js +++ b/Week3/challenges/4-bank-account.js @@ -27,11 +27,27 @@ const bankAccount = { ], }; +const doTransaction = (amount, onSuccess, onFail, reason) => { + const newAmount = bankAccount.currentBalance - amount; + if (newAmount < 0) { + onFail(); + } else { + bankAccount.transactions.push({ + prevAmount: bankAccount.currentBalance, + newAmount, + reason, + }); + bankAccount.currentBalance = newAmount; + onSuccess(); + } +}; + const donateMoney = (amount, onSuccess, onFail) => { - // TODO complete this function + doTransaction(amount, onSuccess, onFail, "Donation"); }; + const payRent = (amount, onSuccess, onFail) => { - // TODO complete this function + doTransaction(amount, onSuccess, onFail, "Rent"); }; /** 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..fe66a9d 100644 --- a/Week3/prep-exercises/1-hyf-program/1-find-mentors.js +++ b/Week3/prep-exercises/1-hyf-program/1-find-mentors.js @@ -8,10 +8,12 @@ import { modules, students, mentors, classes } from "./hyf.js"; * ['John', 'Mary'] */ const possibleMentorsForModule = (moduleName) => { - // TODO complete this function -}; -// You can uncomment out this line to try your function -// console.log(possibleMentorsForModule('using-apis')); + return mentors + .filter(mentor => mentor.canTeach.includes(moduleName)) + .map(mentor => mentor.name) +} +console.log(possibleMentorsForModule('using-apis')); + /** * Tjebbe wants to make it even easier for himself. @@ -20,7 +22,7 @@ const possibleMentorsForModule = (moduleName) => { * It should return a single name. */ const findMentorForModule = (moduleName) => { - // TODO complete this function + return possibleMentorsForModule(moduleName)[Math.floor(Math.random()*possibleMentorsForModule(moduleName).length)] }; -// 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..b87115b 100644 --- a/Week3/prep-exercises/1-hyf-program/2-class-list.js +++ b/Week3/prep-exercises/1-hyf-program/2-class-list.js @@ -12,17 +12,30 @@ import { modules, students, mentors, classes } from "./hyf.js"; * [{ name: 'John', role: 'student' }, { name: 'Mary', role: 'mentor' }] */ const getPeopleOfClass = (className) => { - // TODO complete this function + const findCurrentModule = classes + .filter(classN => classN.name.includes(className)) + .map(classN => classN.currentModule); + + const findTeachers = mentors + .filter(mentor => mentor.nowTeaching == findCurrentModule) + .map(({name}) => ({name, role: 'mentor' })); + + const findStudents = students + .filter(student => student.class == className) + .map(({name}) => ({name, role: 'student' })); + +return [...findTeachers, ...findStudents]; }; + // 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. * First find the active classes, then for each get the people of that class. * * Should return an object with the class names as properties. - * Each class name property contains an array identical to the return from `getPeopleFromClass`. So something like: + * Each class name property contains an array identical to the return from getPeopleOfClass. So something like: * * { * class34: [{ name: 'John', role: 'student' }, { name: 'Mary', role: 'mentor' }], @@ -30,7 +43,19 @@ const getPeopleOfClass = (className) => { * } */ const getActiveClasses = () => { - // TODO complete this function + + const activeClasses = classes + .filter(activeClass => activeClass.active == true); + + const result = {}; + activeClasses.map(activeClass => { + result[activeClass.name] = getPeopleOfClass(activeClass.name); + }); + + return result; + }; // You can uncomment out this line to try your function -// console.log(getActiveClasses()); +console.log(getActiveClasses()); + + diff --git a/Week3/prep-exercises/1-hyf-program/hyf.js b/Week3/prep-exercises/1-hyf-program/hyf.js index c06c02c..08b8a7a 100644 --- a/Week3/prep-exercises/1-hyf-program/hyf.js +++ b/Week3/prep-exercises/1-hyf-program/hyf.js @@ -1,84 +1,84 @@ export const modules = [ - { name: "html-css", displayName: "HTML/CSS" }, - { name: "javascript", displayName: "JavaScript" }, - { name: "browsers", displayName: "Browsers" }, - { name: "using-apis", displayName: "Using APIs" }, - { name: "node", displayName: "Node.js" }, - { name: "databases", displayName: "Databases" }, - { name: "react", displayName: "React" }, - { name: "project", displayName: "Project" }, + { name: "html-css", displayName: "HTML/CSS" }, + { name: "javascript", displayName: "JavaScript" }, + { name: "browsers", displayName: "Browsers" }, + { name: "using-apis", displayName: "Using APIs" }, + { name: "node", displayName: "Node.js" }, + { name: "databases", displayName: "Databases" }, + { name: "react", displayName: "React" }, + { name: "project", displayName: "Project" }, ]; export const classes = [ - { - name: "class32", - startDate: "23-3-2021", - active: false, - graduationDate: "7-11-2021", - }, - { - name: "class33", - startDate: "28-5-2021", - active: false, - graduationDate: "7-11-2021", - }, - { - name: "class34", - startDate: "2-9-2021", - active: true, - currentModule: "react", - }, - { - name: "class35", - startDate: "14-11-2021", - active: true, - currentModule: "using-apis", - }, - { - name: "class36", - startDate: "5-1-2022", - active: true, - currentModule: "javascript", - }, + { + name: "class32", + startDate: "23-3-2021", + active: false, + graduationDate: "7-11-2021", + }, + { + name: "class33", + startDate: "28-5-2021", + active: false, + graduationDate: "7-11-2021", + }, + { + name: "class34", + startDate: "2-9-2021", + active: true, + currentModule: "react", + }, + { + name: "class35", + startDate: "14-11-2021", + active: true, + currentModule: "using-apis", + }, + { + name: "class36", + startDate: "5-1-2022", + active: true, + currentModule: "javascript", + }, ]; export const students = [ - { name: "Fede", class: "class33", gitHubName: "fedefu", graduated: false }, - { name: "Tjebbe", class: "class32", gitHubName: "Tjebbee", graduated: true }, - { name: "Rob", class: "class34", gitHubName: "robvk", graduated: false }, - { - name: "Wouter", - class: "class35", - gitHubName: "wouterkleijn", - graduated: false, - }, + { name: "Fede", class: "class33", gitHubName: "fedefu", graduated: false }, + { name: "Tjebbe", class: "class32", gitHubName: "Tjebbee", graduated: true }, + { name: "Rob", class: "class34", gitHubName: "robvk", graduated: false }, + { + name: "Wouter", + class: "class35", + gitHubName: "wouterkleijn", + graduated: false, + }, ]; export const mentors = [ - { - name: "Stas", - canTeach: ["javascript", "browsers", "using-apis"], - nowTeaching: "javascript", - }, - { - name: "Andrej", - canTeach: ["using-apis", "node"], - }, - { - name: "Shriyans", - canTeach: ["react"], - nowTeaching: "react", - }, - { - name: "Yash", - canTeach: ["javascript", "using-apis"], - }, - { - name: "Rohan", - canTeach: ["html/css/git", "javascript", "node"], - }, - { - name: "Collin", - canTeach: ["browsers", "using-apis", "node"], - }, + { + name: "Stas", + canTeach: ["javascript", "browsers", "using-apis"], + nowTeaching: "javascript", + }, + { + name: "Andrej", + canTeach: ["using-apis", "node"], + }, + { + name: "Shriyans", + canTeach: ["react"], + nowTeaching: "react", + }, + { + name: "Yash", + canTeach: ["javascript", "using-apis"], + }, + { + name: "Rohan", + canTeach: ["html/css/git", "javascript", "node"], + }, + { + name: "Collin", + canTeach: ["browsers", "using-apis", "node"], + }, ]; diff --git a/Week4/prep-exercises/1-wallet/ex2-classes.js b/Week4/prep-exercises/1-wallet/ex2-classes.js index f016137..01e4233 100644 --- a/Week4/prep-exercises/1-wallet/ex2-classes.js +++ b/Week4/prep-exercises/1-wallet/ex2-classes.js @@ -1,6 +1,8 @@ import eurosFormatter from './euroFormatter.js'; class Wallet { + #dailyAllowance = 40; + #dayTotalWithdrawals = 0; #name; #cash; @@ -23,7 +25,13 @@ class Wallet { return 0; } + if (this.#dayTotalWithdrawals + amount > this.#dailyAllowance) { + console.log(`Insufficient remaining daily allowance!`); + return 0; + } + this.#cash -= amount; + this.#dayTotalWithdrawals += amount; return amount; } @@ -37,6 +45,17 @@ class Wallet { 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)}` @@ -50,6 +69,9 @@ function main() { const walletJane = new Wallet('Jane', 20); walletJack.transferInto(walletJoe, 50); + walletJack.setDailyAllowance(80); + walletJack.transferInto(walletJoe, 50); + 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..a6729e8 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; }, @@ -29,6 +37,17 @@ function createWallet(name, cash = 0) { wallet.deposit(withdrawnAmount); }, + setDailyAllowance(newAllowance) { + this._dailyAllowance = newAllowance; + console.log( + `Daily allowance set to: ${eurosFormatter.format(newAllowance)}` + ); + }, + + resetDailyAllowance() { + this._dayTotalWithdrawals = 0; + }, + reportBalance: function () { console.log( `Name: ${this._name}, balance: ${eurosFormatter.format(this._cash)}` @@ -47,6 +66,9 @@ function main() { const walletJane = createWallet('Jane', 20); walletJack.transferInto(walletJoe, 50); + walletJack.setDailyAllowance(80); + walletJack.transferInto(walletJoe, 50); + 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..ad38312 100644 --- a/Week4/prep-exercises/1-wallet/ex4-object-shared-methods.js +++ b/Week4/prep-exercises/1-wallet/ex4-object-shared-methods.js @@ -10,7 +10,13 @@ function withdraw(amount) { return 0; } + if (this._dayTotalWithdrawals + amount > this._dailyAllowance) { + console.log(`Insufficient remaining daily allowance!`); + return 0; + } + this._cash -= amount; + this._dayTotalWithdrawals += amount; return amount; } @@ -24,6 +30,17 @@ function transferInto(wallet, amount) { wallet.deposit(withdrawnAmount); } +function setDailyAllowance(newAllowance) { + this._dailyAllowance = newAllowance; + console.log( + `Daily allowance set to: ${eurosFormatter.format(newAllowance)}` + ); +} + +function resetDailyAllowance() { + this._dayTotalWithdrawals = 0; +} + function reportBalance() { console.log( `Name: ${this._name}, balance: ${eurosFormatter.format(this._cash)}` @@ -38,11 +55,15 @@ function createWallet(name, cash = 0) { return { _name: name, _cash: cash, + _dailyAllowance : 40, + _dayTotalWithdrawals : 0, deposit, withdraw, transferInto, reportBalance, getName, + setDailyAllowance, + resetDailyAllowance }; } @@ -52,6 +73,9 @@ function main() { const walletJane = createWallet('Jane', 20); walletJack.transferInto(walletJoe, 50); + walletJack.setDailyAllowance(80); + walletJack.transferInto(walletJoe, 50); + 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..3372a55 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) { @@ -15,6 +17,11 @@ Wallet.prototype.withdraw = function (amount) { return 0; } + if (this._dayTotalWithdrawals + amount > this._dailyAllowance) { + console.log(`Insufficient remaining daily allowance!`); + return 0; + } + this._cash -= amount; return amount; }; @@ -29,6 +36,17 @@ Wallet.prototype.transferInto = function (wallet, amount) { wallet.deposit(withdrawnAmount); }; +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.reportBalance = function () { console.log( `Name: ${this._name}, balance: ${eurosFormatter.format(this._cash)}` @@ -45,6 +63,9 @@ function main() { const walletJane = new Wallet('Jane', 20); walletJack.transferInto(walletJoe, 50); + walletJack.setDailyAllowance(80); + walletJack.transferInto(walletJoe, 50); + walletJane.transferInto(walletJoe, 25); walletJane.deposit(20);