diff --git a/Week1/practice-exercises/1-remove-the-comma.js b/Week1/practice-exercises/1-remove-the-comma.js index b71cffd..dbfd1fc 100644 --- a/Week1/practice-exercises/1-remove-the-comma.js +++ b/Week1/practice-exercises/1-remove-the-comma.js @@ -7,6 +7,8 @@ let myString = 'hello,this,is,a,difficult,to,read,sentence'; +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..c0154e5 100644 --- a/Week1/practice-exercises/2-even-odd-reporter.js +++ b/Week1/practice-exercises/2-even-odd-reporter.js @@ -7,3 +7,13 @@ * 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} even!`); + } + else{ + console.log(`The number ${i} odd!`); + } + } diff --git a/Week1/practice-exercises/3-recipe-card.js b/Week1/practice-exercises/3-recipe-card.js index 24bcb54..bd6acdf 100644 --- a/Week1/practice-exercises/3-recipe-card.js +++ b/Week1/practice-exercises/3-recipe-card.js @@ -12,3 +12,18 @@ * Ingredients: 4 eggs, 2 strips of bacon, 1 tsp salt/pepper */ +let myOmeletteRecipe = {}; + +myOmeletteRecipe = { + title: "Omelette", + servingNum: 2, + ingredients: ["4 eggs", "2 strips of bacon", "1 tsp salt/pepper"] +}; +console.log('Meal name:', myOmeletteRecipe.title); +console.log('Serves:', myOmeletteRecipe.servingNum); + + +console.log("Ingredients:", myOmeletteRecipe.ingredients.join(', ')); + + + diff --git a/Week1/practice-exercises/4-reading-list.js b/Week1/practice-exercises/4-reading-list.js index f535657..dda064d 100644 --- a/Week1/practice-exercises/4-reading-list.js +++ b/Week1/practice-exercises/4-reading-list.js @@ -9,3 +9,33 @@ * If you haven't read it log a string like You still need to read "The Lord of the Rings" */ +let books = [3]; + +books = [ + { + title: "The Brief History of Time", + author: "Stephen Hawking", + isRead: true + }, + { + title: "The Lord of the Rings", + author: "Joe Doe", + isRead: false + }, + { + title: "The Cosmos", + author: "Carl Sagan", + isRead: true + }, +] + +for(book of books) + { + if(book.isRead){ + console.log(`You already read \"${book.title} by ${book.author}\"`); + }else{ + console.log(`You still need to read \"${book.title} by ${book.author}\"`); + } + } + + diff --git a/Week1/practice-exercises/5-who-wants-a-drink.js b/Week1/practice-exercises/5-who-wants-a-drink.js index f37f02b..d165d64 100644 --- a/Week1/practice-exercises/5-who-wants-a-drink.js +++ b/Week1/practice-exercises/5-who-wants-a-drink.js @@ -8,4 +8,31 @@ */ // 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 = []; +let loops = 5; + +while(loops > 0){ + const drinkType = drinkTypes[Math.floor(Math.random()*3)]; + const maxNumOfDrinkType = 2; + + const countDrinkType = drinkTray.filter(function(drink) { + return drink === drinkType; + }).length; + + if(countDrinkType === maxNumOfDrinkType){ + continue; + } else{ + drinkTray.unshift(drinkType); + loops--; + } +} + +if(!drinkTray.length){ + console.log("I didn't brought drinks."); +}else{ + console.log(`Hey guys I brought ${drinkTray.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..9fee179 100644 --- a/Week1/prep-exercises/1-traffic-light/traffic-light-1.js +++ b/Week1/prep-exercises/1-traffic-light/traffic-light-1.js @@ -8,7 +8,7 @@ const trafficLight = { }; let rotations = 0; -while (rotations < 2) { +do { const currentState = trafficLight.state; console.log("The traffic light is on", currentState); @@ -16,7 +16,22 @@ while (rotations < 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 rotations and turn it green -} + + if(currentState === "green") + { + trafficLight.state = "orange"; + } + else if(currentState === "orange") + { + trafficLight.state = "red"; + } + else if(currentState === "red") + { + rotations += 1; + trafficLight.state = "green"; + } + +}while(rotations < 2) ; /** * The output should be: 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..d70be4b 100644 --- a/Week1/prep-exercises/1-traffic-light/traffic-light-2.js +++ b/Week1/prep-exercises/1-traffic-light/traffic-light-2.js @@ -8,17 +8,19 @@ const trafficLight = { possibleStates: ["green", "orange", "red"], stateIndex: 0, }; - +const numOfPossibleStates = trafficLight.possibleStates.length; let cycle = 0; -while (cycle < 2) { +do { const currentState = trafficLight.possibleStates[trafficLight.stateIndex]; console.log("The traffic light is on", currentState); + + if(currentState === "red"){ + cycle += 1; + } + trafficLight.stateIndex = (trafficLight.stateIndex + 1) % numOfPossibleStates; + //trafficLight.stateIndex = (trafficLight.stateIndex < numOfPossibleStates - 1) ? trafficLight.stateIndex + 1 : 0; - // 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 cycles and turn it green -} +}while (cycle < 2); /** * 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..e3b7676 100644 --- a/Week2/prep-exercises/1-traffic-light/traffic-light.js +++ b/Week2/prep-exercises/1-traffic-light/traffic-light.js @@ -6,17 +6,11 @@ */ 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 + return (trafficLight.stateIndex + 1) % trafficLight.possibleStates.length; } // This function loops for the number of seconds specified by the `secs` diff --git a/Week2/prep-exercises/2-experiments/index.js b/Week2/prep-exercises/2-experiments/index.js index 7e5aa92..99197ea 100644 --- a/Week2/prep-exercises/2-experiments/index.js +++ b/Week2/prep-exercises/2-experiments/index.js @@ -2,45 +2,29 @@ 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. + for(let ii = 0; ii < sampleSize; ii++){ + let randomNumber = Math.floor(Math.random() * 6) + 1; + valueCounts[(randomNumber - 1)]++; + } const results = []; + let sum = valueCounts.reduce((accumulator, value) => accumulator + value, 0); - // 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(let value of valueCounts){ + let percentage = (value / sum) * 100; + results.push(percentage.toFixed(2)); + } 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 + for(let sample of sampleSizes){ + const results = runExperiment(sample); + const formattedResults = `[ ${ results.map(result => `'${result}'`).join(', ') }] ${sample}`; + console.log(formattedResults); + } } main(); diff --git a/Week3/challenges/1-sum-entries.js b/Week3/challenges/1-sum-entries.js index f7dd419..12caa69 100644 --- a/Week3/challenges/1-sum-entries.js +++ b/Week3/challenges/1-sum-entries.js @@ -9,8 +9,17 @@ 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 +const addResult = 2020; + +for(let ii = 0; ii < list.length; ii++){ + for(let jj = ii + 1; jj < list.length; jj++){ + if(list[ii] + list[jj] === addResult) { + result = list[ii] * list[jj]; + // break statement here + } + } + // break statement here +} // TEST CODE, do not change diff --git a/Week3/challenges/2-sum-three-entries.js b/Week3/challenges/2-sum-three-entries.js index f5f8773..310afa8 100644 --- a/Week3/challenges/2-sum-three-entries.js +++ b/Week3/challenges/2-sum-three-entries.js @@ -9,9 +9,20 @@ 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 +const addUpResult = 2020; +for(let ii = 0; ii < list.length; ii++){ + for(let jj = ii + 1; jj < list.length; jj++){ + for (let kk = ii + 1; kk < list.length; kk++){ + if (list[ii] + list[jj] + list[kk] === addUpResult){ + result = list[ii] * list[jj] * list[kk]; + // break statement here + } + } + // break statement here + } + // break statement here +} // 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..a2e2ccf 100644 --- a/Week3/challenges/3-password-validation.js +++ b/Week3/challenges/3-password-validation.js @@ -20,4 +20,24 @@ 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 +]; + +const splitStr = input => input.split('-').map(char => Number(char)); + +const validatePassword = passwordList => { + passwordList.forEach(({times, letter, password}) => { + + const passwordChar = password.split(''); + let letterCounts = passwordChar.filter(character => { return character === letter; }).length; + + const result = splitStr(times); + if(letterCounts < result[0] || letterCounts > result[1]){ + console.log(`'${password}' is INVALID ${letter} is present ${letterCounts} times and should have been present at least ${result[0]} and at most ${result[1]} times`); + }else{ + console.log(`'${password}' is VALID ${letter} is present ${letterCounts} times and should have been present at least ${result[0]} and at most ${result[1]} times`); + } + }); +}; + +validatePassword(passwordList) + diff --git a/Week3/challenges/4-bank-account.js b/Week3/challenges/4-bank-account.js index 8f0f035..24ec5fa 100644 --- a/Week3/challenges/4-bank-account.js +++ b/Week3/challenges/4-bank-account.js @@ -27,11 +27,26 @@ const bankAccount = { ], }; +const createTransaction = (amount, onSuccess, onFail, reason) => { + if (amount > bankAccount.currentBalance) { + onFail(); + return 0; + } + + bankAccount.transactions.push({ + prevAmount: bankAccount.currentBalance, + newAmount: bankAccount.currentBalance - amount, + reason: reason + }); + bankAccount.currentBalance -= amount; + onSuccess(); +}; + const donateMoney = (amount, onSuccess, onFail) => { - // TODO complete this function + createTransaction(amount, onSuccess, onFail, "Donation"); }; const payRent = (amount, onSuccess, onFail) => { - // TODO complete this function + createTransaction(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..9b280ec 100644 --- a/Week3/prep-exercises/1-hyf-program/1-find-mentors.js +++ b/Week3/prep-exercises/1-hyf-program/1-find-mentors.js @@ -7,11 +7,38 @@ import { modules, students, mentors, classes } from "./hyf.js"; * It should return an array of names. So something like: * ['John', 'Mary'] */ -const possibleMentorsForModule = (moduleName) => { - // TODO complete this function + +// I tried it first with forEach and thought ahh i can use reduce +// const possibleMentorsForModule = (moduleName) => { +// let mentorForModule = []; +// mentors.forEach(mentor => { +// if (mentor.canTeach.includes(moduleName)) { +// mentorForModule.push(mentor.name); +// } +// }); +// return mentorForModule; +// }; + + const possibleMentorsForModule = (moduleName) => { + return mentors.reduce((acc, mentor) => { + if (mentor.canTeach.includes(moduleName)) { + acc.push(mentor.name); + } + return acc; + }, []); + +}; + +export const mentorForModule = (moduleName) => { + return mentors.reduce((acc, mentor) => { + if (mentor.nowTeaching === moduleName) { + acc.push(mentor); + } + return acc; + }, []); }; // 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. @@ -20,7 +47,14 @@ const possibleMentorsForModule = (moduleName) => { * It should return a single name. */ const findMentorForModule = (moduleName) => { - // TODO complete this function + const result = possibleMentorsForModule(moduleName); + if( !result ) return `No mentor found for module ${moduleName}`; + + if(result.length === 1){ + return result[0]; + } + const randomNum = Math.floor(Math.random() * result.length) + return result[randomNum]; }; // You can uncomment out this line to try your function // 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..9616a79 100644 --- a/Week3/prep-exercises/1-hyf-program/2-class-list.js +++ b/Week3/prep-exercises/1-hyf-program/2-class-list.js @@ -1,5 +1,5 @@ import { modules, students, mentors, classes } from "./hyf.js"; - +import { mentorForModule } from "./1-find-mentors.js"; /** * We would like to have a list of everyone that is currently participating in a class. * This means the students, but also the mentors that are currently teaching the class. @@ -11,8 +11,22 @@ import { modules, students, mentors, classes } from "./hyf.js"; * * [{ name: 'John', role: 'student' }, { name: 'Mary', role: 'mentor' }] */ + + +const filterStudentsByClassName = className => { + return students.filter(student => { + return student.class === className && student.graduated === false}) + .map(({name}) => ({name, role: 'student'})); +}; + const getPeopleOfClass = (className) => { - // TODO complete this function + const participatingStudents = filterStudentsByClassName(className); + + const specificClass = classes.find(({name}) => name === className); + const participatingMentors = mentorForModule(specificClass.currentModule) + .map(({name}) => ({name, role:'mentor'})); + + return [...participatingStudents, ...participatingMentors]; }; // You can uncomment out this line to try your function // console.log(getPeopleOfClass('class34')); @@ -30,7 +44,14 @@ const getPeopleOfClass = (className) => { * } */ const getActiveClasses = () => { - // TODO complete this function + const activeClasses = classes + .filter(({active}) => { return active === true }) + .map(({name}) => ({name})); + + return activeClasses.reduce((acc, activeClass) => { + acc[activeClass.name] = getPeopleOfClass(activeClass.name); + return acc; + }, {}); }; // You can uncomment out this line to try your function // console.log(getActiveClasses()); diff --git a/Week4/prep-exercises/1-wallet/ex2-classes.js b/Week4/prep-exercises/1-wallet/ex2-classes.js index f016137..54b2512 100644 --- a/Week4/prep-exercises/1-wallet/ex2-classes.js +++ b/Week4/prep-exercises/1-wallet/ex2-classes.js @@ -3,6 +3,8 @@ import eurosFormatter from './euroFormatter.js'; class Wallet { #name; #cash; + #dailyAllowance = 40; + #dayTotalWithdrawals = 0; constructor(name, cash) { this.#name = name; @@ -23,10 +25,25 @@ 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; } + setDailyAllowance(newAllowance) { + this.#dailyAllowance = newAllowance; + console.log( + `Daily allowance set to: ${eurosFormatter.format(newAllowance)}` + ); + } + resetDailyAllowance() { + this.#dayTotalWithdrawals = 0; + } + transferInto(wallet, amount) { console.log( `Transferring ${eurosFormatter.format(amount)} from ${this.name} to ${ @@ -45,11 +62,12 @@ class Wallet { } function main() { - const walletJack = new Wallet('Jack', 100); + const walletJack = new Wallet('Jack', 500); const walletJoe = new Wallet('Joe', 10); const walletJane = new Wallet('Jane', 20); - walletJack.transferInto(walletJoe, 50); + walletJack.transferInto(walletJoe, 100); + 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..b837b11 100644 --- a/Week4/prep-exercises/1-wallet/ex3-object.js +++ b/Week4/prep-exercises/1-wallet/ex3-object.js @@ -1,9 +1,11 @@ -import eurosFormatter from './euroFormatter.js'; +import eurosFormatter from "./euroFormatter.js"; 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,16 @@ function createWallet(name, cash = 0) { wallet.deposit(withdrawnAmount); }, + setDailyAllowance: function (newAllowance) { + this._dailyAllowance = newAllowance; + console.log( + `Daily allowance set to: ${eurosFormatter.format(newAllowance)}` + ); + }, + + resetDailyAllowance: function () { + this._dayTotalWithdrawals = 0; + }, reportBalance: function () { console.log( `Name: ${this._name}, balance: ${eurosFormatter.format(this._cash)}` @@ -42,11 +60,14 @@ function createWallet(name, cash = 0) { } function main() { - const walletJack = createWallet('Jack', 100); - const walletJoe = createWallet('Joe', 10); - const walletJane = createWallet('Jane', 20); + const walletJack = createWallet("Jack", 100); + const walletJoe = createWallet("Joe", 10); + 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..8a558a9 100644 --- a/Week4/prep-exercises/1-wallet/ex4-object-shared-methods.js +++ b/Week4/prep-exercises/1-wallet/ex4-object-shared-methods.js @@ -1,4 +1,4 @@ -import eurosFormatter from './euroFormatter.js'; +import eurosFormatter from "./euroFormatter.js"; function deposit(amount) { this._cash += amount; @@ -9,7 +9,10 @@ function withdraw(amount) { console.log(`Insufficient funds!`); return 0; } - + if (this._dayTotalWithdrawals + amount > this._dailyAllowance) { + console.log(`Insufficient remaining daily allowance!`); + return 0; + } this._cash -= amount; return amount; } @@ -24,6 +27,14 @@ 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,20 +49,27 @@ function createWallet(name, cash = 0) { return { _name: name, _cash: cash, + _dailyAllowance: 40, + _dayTotalWithdrawals: 0, deposit, withdraw, transferInto, + setDailyAllowance, + resetDailyAllowance, reportBalance, getName, }; } function main() { - const walletJack = createWallet('Jack', 100); - const walletJoe = createWallet('Joe', 10); - const walletJane = createWallet('Jane', 20); + const walletJack = createWallet("Jack", 100); + const walletJoe = createWallet("Joe", 10); + 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..86df39c 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,10 +17,24 @@ Wallet.prototype.withdraw = function (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; }; +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.transferInto = function (wallet, amount) { console.log( `Transferring ${eurosFormatter.format(amount)} from ${ @@ -45,6 +61,7 @@ function main() { const walletJane = new Wallet('Jane', 20); walletJack.transferInto(walletJoe, 50); + walletJack.setDailyAllowance(80); walletJane.transferInto(walletJoe, 25); walletJane.deposit(20);