From fddf32a1f9ca4ec8d1f072a26c6c36ea6c6edb67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Sar=C4=B1ta=C5=9F?= Date: Sat, 20 Apr 2024 00:20:45 +0200 Subject: [PATCH 1/5] js exercises some solutions --- .../practice-exercises/1-remove-the-comma.js | 18 +++++++++++++ .../practice-exercises/2-even-odd-reporter.js | 9 +++++++ Week1/practice-exercises/3-recipe-card.js | 26 +++++++++++++++++++ .../1-traffic-light/traffic-light-1.js | 15 +++++++++++ 4 files changed, 68 insertions(+) diff --git a/Week1/practice-exercises/1-remove-the-comma.js b/Week1/practice-exercises/1-remove-the-comma.js index b71cffd..e61aa51 100644 --- a/Week1/practice-exercises/1-remove-the-comma.js +++ b/Week1/practice-exercises/1-remove-the-comma.js @@ -7,7 +7,25 @@ let myString = 'hello,this,is,a,difficult,to,read,sentence'; +// First Solution // +let result = ''; +// Iterate through each character of string in myString value +for (let i = 0; i < myString.length; i++) { + //If the iterating character is a comma, replace it with a space + if (myString[i] === ',') { + result += ' '; + } + else { + //If the iterating character is not a comma, keep it the same + result += myString[i]; + } +} +result = myString; + +// Second Solution // +//Replace commas with spaces to update the string +myString = myString.split(',').join(' '); /* --- Code that will test your solution, do NOT change. Write above this line --- */ diff --git a/Week1/practice-exercises/2-even-odd-reporter.js b/Week1/practice-exercises/2-even-odd-reporter.js index 6edf23e..8889ccc 100644 --- a/Week1/practice-exercises/2-even-odd-reporter.js +++ b/Week1/practice-exercises/2-even-odd-reporter.js @@ -7,3 +7,12 @@ * 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`) + } +} \ No newline at end of file diff --git a/Week1/practice-exercises/3-recipe-card.js b/Week1/practice-exercises/3-recipe-card.js index 24bcb54..a69f03f 100644 --- a/Week1/practice-exercises/3-recipe-card.js +++ b/Week1/practice-exercises/3-recipe-card.js @@ -12,3 +12,29 @@ * Ingredients: 4 eggs, 2 strips of bacon, 1 tsp salt/pepper */ +/* +Menemen is a popular traditional Turkish dish that includes eggs, tomato, green peppers, and spices such as ground black and pepper cooked in olive oil. +*/ +const myRecipe = { + title: 'Menemen', + servings: 2, + ingredients: [ + '2 eggs', + '2 peeled and grated tomatoes', + '1 onion', + '1 green pepper', + '1 tsp salt/pepper' + ], +}; + +for (let item in myRecipe) { + if (item == 'title') { + console.log(`Meal name: ${myRecipe[item]}`); + } else if (item == 'servings') { + console.log(`Serves: ${myRecipe[item]}`); + } else { + const ingredientList = myRecipe[item]; + + console.log(`Ingedients: ${ingredientList.join(', ')}`); + } +} 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..e6a5461 100644 --- a/Week1/prep-exercises/1-traffic-light/traffic-light-1.js +++ b/Week1/prep-exercises/1-traffic-light/traffic-light-1.js @@ -29,3 +29,18 @@ The traffic light is on orange The traffic light is on red */ + + // We use a switch statement to handle different states of the traffic light + switch (currentState) { + case "green": + trafficLight.state = "orange"; + break; + case "orange": + trafficLight.state = "red"; + break; + case "red": + rotations++; + trafficLight.state = "green"; + break; + } +} From b0f8b3d483dc0f28bd511b7565df0b9b9d673922 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Sar=C4=B1ta=C5=9F?= Date: Sat, 20 Apr 2024 12:10:31 +0200 Subject: [PATCH 2/5] Week2 prep exercies solutions --- Week1/practice-exercises/4-reading-list.js | 15 +++++++++++++++ .../1-traffic-light/traffic-light-2.js | 11 +++++++++++ 2 files changed, 26 insertions(+) diff --git a/Week1/practice-exercises/4-reading-list.js b/Week1/practice-exercises/4-reading-list.js index f535657..eb7c75a 100644 --- a/Week1/practice-exercises/4-reading-list.js +++ b/Week1/practice-exercises/4-reading-list.js @@ -9,3 +9,18 @@ * If you haven't read it log a string like You still need to read "The Lord of the Rings" */ +let books = [ + { title: "The Hobbit", author: "J.R.R. Tolkien", alreadyRead: true }, + { title: "1984", author: "George Orwell", alreadyRead: false }, + { title: "To Kill a Mockingbird", author: "Harper Lee", alreadyRead: true } +]; + +for (let book of books) { + console.log(`${book.title} by ${book.author}`); + + if (book.alreadyRead) { + console.log(`You already read "${book.title}"`); + } else { + console.log(`You still need to read "${book.title}"`); + } +} 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..b49904d 100644 --- a/Week1/prep-exercises/1-traffic-light/traffic-light-2.js +++ b/Week1/prep-exercises/1-traffic-light/traffic-light-2.js @@ -18,6 +18,17 @@ while (cycle < 2) { // if the color is green, turn it orange // if the color is orange, turn it red // if the color is red, add 1 to cycles and turn it green + + if (currentState === "green") { + trafficLight.stateIndex = 1; // Turn it on orange + } + else if (currentState === "orange") { + trafficLight.stateIndex === 2; // Turn it on red + } + else if (currentState === "red") { + trafficLight.stateIndex = 0; // Turn it on green + cycle++; + } } /** From f319fb8b790c06c0033a2a4f8b5138d989298a84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Sar=C4=B1ta=C5=9F?= Date: Sat, 27 Apr 2024 00:35:42 +0200 Subject: [PATCH 3/5] new_commit --- Week1/new.js | 32 +++++++ .../1-traffic-light/traffic-light-1.js | 26 +---- .../1-traffic-light/traffic-light.js | 96 +++++++++++++------ Week2/prep-exercises/2-experiments/index.js | 90 +++++++++++------ 4 files changed, 163 insertions(+), 81 deletions(-) create mode 100644 Week1/new.js diff --git a/Week1/new.js b/Week1/new.js new file mode 100644 index 0000000..f776f4a --- /dev/null +++ b/Week1/new.js @@ -0,0 +1,32 @@ +/* + Exercise 1: Calculate the Sum of Array Elements: + Write a function calculateSum that takes an array of numbers as input and returns the sum of all the elements in the array. +*/ + +const totalNumbers = [6, 7, 8, 6, 6, 6, 9]; + +/* + Exercise 2: Calculate the Average of Array Elements: + Write a function calculateAverage that takes an array of numbers as input and returns the average of all the elements in the array. +*/ +function calAvg(averageNumbers) { + let sum = 0; + for (let i = 0; i < averageNumbers.length; i++) { + sum += averageNumbers[i]; + } + return sum / averageNumbers.length; +} + +const averageNumbers = [6, 3, 48, 4, 12, 8, 16]; +const average = calAvg(averageNumbers); +console.log("Average:", average); + + + + +/* + Exercise 3: Find the Largest Number in an Array: + Write a function findLargestNumber that takes an array of numbers as input and returns the largest number in the array. +*/ + +const largestNumbers = [3, 7, 9, 48, 6, 6, 18]; \ 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 e6a5461..5b45f90 100644 --- a/Week1/prep-exercises/1-traffic-light/traffic-light-1.js +++ b/Week1/prep-exercises/1-traffic-light/traffic-light-1.js @@ -1,8 +1,6 @@ "use strict"; -/** - * The `state` property says what the traffic light's state (i.e. colour) is at - * that moment. - */ + + const trafficLight = { state: "green", }; @@ -12,25 +10,7 @@ while (rotations < 2) { 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 -} - -/** - * The output should be: - -The traffic light is on green -The traffic light is on orange -The traffic light is on red -The traffic light is on green -The traffic light is on orange -The traffic light is on red - -*/ - - // We use a switch statement to handle different states of the traffic light + // Handling the traffic light state transitions switch (currentState) { case "green": trafficLight.state = "orange"; diff --git a/Week2/prep-exercises/1-traffic-light/traffic-light.js b/Week2/prep-exercises/1-traffic-light/traffic-light.js index f4a5c1a..ebe49cd 100644 --- a/Week2/prep-exercises/1-traffic-light/traffic-light.js +++ b/Week2/prep-exercises/1-traffic-light/traffic-light.js @@ -1,33 +1,80 @@ +// "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 +// * functions, as and when needed. +// */ + +// function getCurrentState(trafficLight) { +// // TODO +// // Should return the current state (i.e. colour) of the `trafficLight` +// // object passed as a parameter. +// } + +// 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 +// } + +// // 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 +// } +// } + +// 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); +// } +// } + +// main(); +// /** +// * The output should be: + +// 0 The traffic light is now green +// 1 The traffic light is now orange +// 2 The traffic light is now red +// 3 The traffic light is now green +// 4 The traffic light is now orange +// 5 The traffic light is now red + +// */ + "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 - * functions, as and when needed. - */ function getCurrentState(trafficLight) { - // TODO - // Should return the current state (i.e. colour) 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 + // Increment the state index, wrapping around to 0 if it exceeds the length + // of the possibleStates array. + return (trafficLight.stateIndex + 1) % trafficLight.possibleStates.length; } -// 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 + // Do nothing here } } @@ -47,14 +94,3 @@ function main() { } main(); -/** - * The output should be: - -0 The traffic light is now green -1 The traffic light is now orange -2 The traffic light is now red -3 The traffic light is now green -4 The traffic light is now orange -5 The traffic light is now red - -*/ diff --git a/Week2/prep-exercises/2-experiments/index.js b/Week2/prep-exercises/2-experiments/index.js index 7e5aa92..bc9fa4e 100644 --- a/Week2/prep-exercises/2-experiments/index.js +++ b/Week2/prep-exercises/2-experiments/index.js @@ -1,29 +1,68 @@ +// "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; +// } + +// 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 +// } + +// main(); + "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. + // Step 1: Generate random dice rolls and count occurrences + for (let i = 0; i < sampleSize; i++) { + const roll = Math.floor(Math.random() * 6) + 1; // Generate a random number between 1 and 6 + valueCounts[roll - 1]++; // Increment the corresponding count in valueCounts + } 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. + // Step 2: Calculate the percentage of each value and format the results + for (let count of valueCounts) { + const percentage = ((count / sampleSize) * 100).toFixed(2); // Calculate the percentage and fix to 2 decimal places + results.push(percentage); // Push the formatted percentage to the results array + } return results; } @@ -31,16 +70,11 @@ function runExperiment(sampleSize) { 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 + // Run experiments for different sample sizes and log the results + for (let sampleSize of sampleSizes) { + const percentages = runExperiment(sampleSize); + console.log(percentages, sampleSize); + } } main(); From 76bdeb8b19730a302e82fdb2dfee99ccda66b50c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Sar=C4=B1ta=C5=9F?= Date: Sat, 4 May 2024 21:22:59 +0200 Subject: [PATCH 4/5] Javascript Third week prep-exercises solutions --- .../1-hyf-program/1-find-mentors.js | 27 ++++++++++++++++--- .../1-hyf-program/2-class-list.js | 24 +++++++++++++---- 2 files changed, 42 insertions(+), 9 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..05cff1e 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,24 @@ import { modules, students, mentors, classes } from "./hyf.js"; * ['John', 'Mary'] */ const possibleMentorsForModule = (moduleName) => { - // TODO complete this function + const mentorsForModule = mentors.filter(mentor => + mentor.canTeach.includes(moduleName) + ); + return mentorsForModule.map(mentor => mentor.name); }; + +/* +*** A different Solution Method *** + +const possibleMentorsForModule = (moduleName) => { + return mentors.flatMap(mentor => + mentor.canTeach.includes(moduleName) ? mentor.name : [] + ); +}; +*/ + // You can uncomment out this line to try your function -// console.log(possibleMentorsForModule('using-apis')); + console.log(possibleMentorsForModule('using-apis')); /** * Tjebbe wants to make it even easier for himself. @@ -19,8 +33,13 @@ const possibleMentorsForModule = (moduleName) => { * * It should return a single name. */ + const findMentorForModule = (moduleName) => { - // TODO complete this function + const mentorsForModule = mentors.filter(mentor => + mentor.canTeach.includes(moduleName) + ); + const randomIndex = Math.floor(Math.random() * mentorsForModule.length); + return mentorsForModule[randomIndex].name; }; // 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..55fafd6 100644 --- a/Week3/prep-exercises/1-hyf-program/2-class-list.js +++ b/Week3/prep-exercises/1-hyf-program/2-class-list.js @@ -11,11 +11,19 @@ import { modules, students, mentors, classes } from "./hyf.js"; * * [{ name: 'John', role: 'student' }, { name: 'Mary', role: 'mentor' }] */ -const getPeopleOfClass = (className) => { - // TODO complete this function +const getPeopleOfClass = className => { + const classInfo = classes.find(x => x.name === className); + if (!classInfo) return []; + + const studentsOfClass = students.filter(student => student.class === className).map(student => ({ name: student.name, role: "student" })); + + const mentorsOfClass = mentors.filter(mentor => mentor.nowTeaching === classInfo.currentModule).map(mentor => ({ name: mentor.name, role: "mentor" })); + + return [...studentsOfClass, ...mentorsOfClass]; }; + // 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 +38,13 @@ const getPeopleOfClass = (className) => { * } */ const getActiveClasses = () => { - // TODO complete this function + return classes + .filter(x => x.active) + .reduce((activeClasses, currentClass) => { + activeClasses[currentClass.name] = getPeopleOfClass(currentClass.name); + return activeClasses; + }, {}); }; + // You can uncomment out this line to try your function -// console.log(getActiveClasses()); +console.log(getActiveClasses()); From 8ce63b1072264136792f1c8e34f0d545720fac0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mustafa=20Sar=C4=B1ta=C5=9F?= Date: Sat, 11 May 2024 19:50:57 +0200 Subject: [PATCH 5/5] JS Week4 prep-exercises --- Week4/prep-exercises/1-wallet/ex2-classes.js | 23 ++++++++++++++++++- Week4/prep-exercises/1-wallet/ex3-object.js | 18 ++++++++++++++- .../1-wallet/ex4-object-shared-methods.js | 17 +++++++++++++- .../prep-exercises/1-wallet/ex5-prototype.js | 19 ++++++++++++++- 4 files changed, 73 insertions(+), 4 deletions(-) diff --git a/Week4/prep-exercises/1-wallet/ex2-classes.js b/Week4/prep-exercises/1-wallet/ex2-classes.js index f016137..9d2d9f7 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; + #dailyAllowance; + #dayTotalWithdrawals; constructor(name, cash) { this.#name = name; this.#cash = cash; + this.#dailyAllowance = 40; + this.#dayTotalWithdrawals = 0; } get name() { @@ -23,7 +27,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; } @@ -42,6 +52,17 @@ class Wallet { `Name: ${this.name}, balance: ${eurosFormatter.format(this.#cash)}` ); } + + resetDailyAllowance() { + this.#dayTotalWithdrawals = 0; + } + + setDailyAllowance(newAllowance) { + this.#dailyAllowance = newAllowance; + console.log( + `Daily allowance set to: ${eurosFormatter.format(newAllowance)}` + ); + } } function main() { @@ -60,4 +81,4 @@ function main() { walletJane.reportBalance(); } -main(); +main(); \ No newline at end of file diff --git a/Week4/prep-exercises/1-wallet/ex3-object.js b/Week4/prep-exercises/1-wallet/ex3-object.js index e94faac..b594719 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; }, @@ -38,6 +46,14 @@ function createWallet(name, cash = 0) { getName: function () { return this._name; }, + + resetDailyAllowance: function () { + this._dayTotalWithdrawals = 0; + }, + + setDailyAllowance: function (newAllowance) { + this._dailyAllowance = newAllowance; + } }; } @@ -57,4 +73,4 @@ function main() { walletJane.reportBalance(); } -main(); +main(); \ No newline at end of file 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..a0d8a69 100644 --- a/Week4/prep-exercises/1-wallet/ex4-object-shared-methods.js +++ b/Week4/prep-exercises/1-wallet/ex4-object-shared-methods.js @@ -10,6 +10,11 @@ function withdraw(amount) { return 0; } + if (this._dayTotalWithdrawals + amount > this._dailyAllowance) { + console.log(`Insufficient remaining daily allowance!`); + return 0; + } + this._cash -= amount; return amount; } @@ -34,10 +39,20 @@ function getName() { return this._name; } +function resetDailyAllowance() { + this._dayTotalWithdrawals = 0; +} + +function setDailyAllowance(newAllowance) { + this._dailyAllowance = newAllowance; +} + function createWallet(name, cash = 0) { return { _name: name, _cash: cash, + _dailyAllowance: 40, + _dayTotalWithdrawals: 0, deposit, withdraw, transferInto, @@ -62,4 +77,4 @@ function main() { walletJane.reportBalance(); } -main(); +main(); \ No newline at end of file diff --git a/Week4/prep-exercises/1-wallet/ex5-prototype.js b/Week4/prep-exercises/1-wallet/ex5-prototype.js index 7cba410..dde5015 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; }; @@ -39,6 +46,16 @@ Wallet.prototype.getName = function () { return this._name; }; +Wallet.prototype.resetDailyAllowance = function () { + this._dayTotalWithdrawals = 0; +}; + +Wallet.prototype.setDailyAllowance = function (newAllowance) { + this._dailyAllowance = newAllowance; +}; + + + function main() { const walletJack = new Wallet('Jack', 100); const walletJoe = new Wallet('Joe', 10); @@ -55,4 +72,4 @@ function main() { walletJane.reportBalance(); } -main(); +main(); \ No newline at end of file