From dcc7128980647277526a37bb34f6e4dc22c68e09 Mon Sep 17 00:00:00 2001 From: Hanna Date: Sat, 20 Apr 2024 15:52:11 +0200 Subject: [PATCH 1/4] finished the practice exercises & prep exercises --- .../practice-exercises/1-remove-the-comma.js | 3 ++- .../practice-exercises/2-even-odd-reporter.js | 11 ++++++++- Week1/practice-exercises/3-recipe-card.js | 24 +++++++++++++++++++ Week1/practice-exercises/4-reading-list.js | 10 ++++++++ .../practice-exercises/5-who-wants-a-drink.js | 23 +++++++++++++++++- .../1-traffic-light/traffic-light-1.js | 8 +++++++ .../1-traffic-light/traffic-light-2.js | 10 +++++++- 7 files changed, 85 insertions(+), 4 deletions(-) diff --git a/Week1/practice-exercises/1-remove-the-comma.js b/Week1/practice-exercises/1-remove-the-comma.js index b71cffd..95738ee 100644 --- a/Week1/practice-exercises/1-remove-the-comma.js +++ b/Week1/practice-exercises/1-remove-the-comma.js @@ -6,7 +6,8 @@ */ let myString = 'hello,this,is,a,difficult,to,read,sentence'; - +myString = myString.split(",").join(" "); +console.log(myString); /* --- 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..46c0a6d 100644 --- a/Week1/practice-exercises/2-even-odd-reporter.js +++ b/Week1/practice-exercises/2-even-odd-reporter.js @@ -1,5 +1,5 @@ /** - * Report whether or not a number is odd/even! + * Report whether a number is odd/even! * * Create a for loop, that iterates from 0 to 20. * Create a conditional statement that checks if the value of the counter variable is odd or even. @@ -7,3 +7,12 @@ * If it's even, log to the console The number [PUT_NUMBER_HERE] is even!. */ +function oddCheck(counter) { + let resultOfCheck = counter % 2 === 0? 'even' : 'odd'; + console.log(`The number ${counter} is ${resultOfCheck}`) +} + + +oddCheck(2); +oddCheck(5); +oddCheck(0); \ 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..21f9bf6 100644 --- a/Week1/practice-exercises/3-recipe-card.js +++ b/Week1/practice-exercises/3-recipe-card.js @@ -12,3 +12,27 @@ * Ingredients: 4 eggs, 2 strips of bacon, 1 tsp salt/pepper */ + +const recipe = {}; +recipe.title = "Omelette"; +recipe.servings = 2; +recipe.ingredients = ["4 eggs", "2 strips of bacon", "1 tsp salt/pepper"]; + +for (const key in recipe) { + //switch for more descriptive logging + switch(key) { + case 'title': + console.log(`Meal name: ${recipe[key]}`); + break; + case 'servings': + console.log(`Serves: ${recipe[key]}`); + break; + case 'ingredients': + console.log(`Ingredients: ${recipe[key].join(', ')}`); + break; + default: + console.log(`${key}: ${recipe[key]}`); + break; + } +} + diff --git a/Week1/practice-exercises/4-reading-list.js b/Week1/practice-exercises/4-reading-list.js index f535657..11b1f44 100644 --- a/Week1/practice-exercises/4-reading-list.js +++ b/Week1/practice-exercises/4-reading-list.js @@ -9,3 +9,13 @@ * If you haven't read it log a string like You still need to read "The Lord of the Rings" */ +const books= [ + { title: "The Hobbit", author: "J.R.R. Tolkien", alreadyRead: false }, + { title: "The Comedy Bible", author: "J. Carter", alreadyRead: true }, + { title: "The Enchiridion", author: "Epictetus", alreadyRead: false } +]; + +for (book of books) { + const status = book.alreadyRead === true? 'You have already read':'You still need to read'; + console.log(`${status} ${book.title} by ${book.author}.`); +} \ 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..66e8070 100644 --- a/Week1/practice-exercises/5-who-wants-a-drink.js +++ b/Week1/practice-exercises/5-who-wants-a-drink.js @@ -8,4 +8,25 @@ */ // There are 3 different types of drinks: -const drinkTypes = ['cola', 'lemonade', 'water']; \ No newline at end of file +const drinkTypes = ['cola', 'lemonade', 'water']; + +const drinkTray = []; +const drinkLimits = { cola: 0, lemonade: 0, water: 0 }; +const maxPerDrink = 2; + +for (let i = 0; i < 5; i++) { + let drinkAdded = false; + while (!drinkAdded) { + // Randomly select a drink from the drinkTypes array + const drink = drinkTypes[Math.floor(Math.random() * drinkTypes.length)]; + + // Check if we can add this drink to the tray + if (drinkLimits[drink] < maxPerDrink) { + drinkTray.push(drink); + drinkLimits[drink] += 1; + drinkAdded = true; + } + } +} + +console.log(`Hey guys, I brought a ${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..b1616fd 100644 --- a/Week1/prep-exercises/1-traffic-light/traffic-light-1.js +++ b/Week1/prep-exercises/1-traffic-light/traffic-light-1.js @@ -16,6 +16,14 @@ 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 ++; + trafficLight.state = "green" + } } /** 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..b051f06 100644 --- a/Week1/prep-exercises/1-traffic-light/traffic-light-2.js +++ b/Week1/prep-exercises/1-traffic-light/traffic-light-2.js @@ -1,6 +1,6 @@ "use strict"; /** - * The `possibleStates` property define the states (in this case: colours) + * The `possibleStates` property defines the states (in this case: colours) * in which the traffic light can be. * The `stateIndex` property indicates which of the possible states is current. */ @@ -18,6 +18,14 @@ 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 ++; + } else if (currentState === "orange") { + trafficLight.stateIndex ++; + } else if (currentState === "red") { + cycle ++; + trafficLight.stateIndex = 0; + } } /** From 458df41366d556465d9626f94b24673c31224033 Mon Sep 17 00:00:00 2001 From: Hanna Date: Sat, 27 Apr 2024 13:17:05 +0200 Subject: [PATCH 2/4] exercise week 2: done --- Week2/prep-exercises/1-traffic-light/README.md | 7 +++++++ .../1-traffic-light/traffic-light.js | 2 ++ Week2/prep-exercises/2-experiments/README.md | 5 +++++ Week2/prep-exercises/2-experiments/index.js | 16 ++++++++++++++++ 4 files changed, 30 insertions(+) diff --git a/Week2/prep-exercises/1-traffic-light/README.md b/Week2/prep-exercises/1-traffic-light/README.md index b3c3748..e9420a4 100644 --- a/Week2/prep-exercises/1-traffic-light/README.md +++ b/Week2/prep-exercises/1-traffic-light/README.md @@ -5,5 +5,12 @@ In the previous week we started with our traffic light. Now that we also know wh ## Things to think about - This time the loop was changed to a for loop that will run the code 6 times. Why was that needed? + - The logic has changed: now the cycle is a number of traffic light changes - Why was the trafficLight added to the `main` function and not left at the top of the file? + - Now we use the local scope. It minimizes the risk of interaction with other parts of the program. + - Usually we want the code to be as predictable as possible. Less unwanted interactions == more predictability. + - This way main function is more reusable. - What do you think is the advantage of having the `getCurrentTrafficLightState` and `getNextStateIndex` functions? + - Since they are simple, it's easy to reuse them in other functions. + - The reason why we haven't declared them in main() could be that we want to reuse them elsewhere + - The functions are clear - it would be easier for others to understand what's happenign in the code diff --git a/Week2/prep-exercises/1-traffic-light/traffic-light.js b/Week2/prep-exercises/1-traffic-light/traffic-light.js index f4a5c1a..75cb18f 100644 --- a/Week2/prep-exercises/1-traffic-light/traffic-light.js +++ b/Week2/prep-exercises/1-traffic-light/traffic-light.js @@ -9,6 +9,7 @@ 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) { @@ -17,6 +18,7 @@ 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 + 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/README.md b/Week2/prep-exercises/2-experiments/README.md index a0e63ca..b3ab1b2 100644 --- a/Week2/prep-exercises/2-experiments/README.md +++ b/Week2/prep-exercises/2-experiments/README.md @@ -11,4 +11,9 @@ In this prep exercise we are using the `Math.random()` function to simulate thro ## Things to think about - The `valueCounts` is implemented as an array. Do you think there is another way to store this? Why do you think the decision was made to go with an array? + - An object or map could be used to make the code more readable (since it allows to write the 'key: value' pairs, with dice value and count of times the value was thrown) + - But since the function is not super intricate, it's still easy to read. So I'd leave it as it is. - What do you think about the code division? Would you add another function or maybe remove one? Why? + - I wouldn't add any other functions, I'd use as fewer lines of code as possible + - Adding more functions could unnecessarily overcomplicate things. + - With more abstraction, the function would work slower: more abstraction means more time to communicate between separate logic units diff --git a/Week2/prep-exercises/2-experiments/index.js b/Week2/prep-exercises/2-experiments/index.js index 7e5aa92..ec68c41 100644 --- a/Week2/prep-exercises/2-experiments/index.js +++ b/Week2/prep-exercises/2-experiments/index.js @@ -13,6 +13,11 @@ function runExperiment(sampleSize) { // 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++) { + let randomIndex = Math.floor(Math.random() * 6); + valueCounts[randomIndex] ++; + } + const results = []; // TODO @@ -25,6 +30,12 @@ function runExperiment(sampleSize) { // two decimals, e.g. '14.60'. // 3. Then push that string onto the `results` array. + for (let count of valueCounts) { + const percentageThrown = (count / sampleSize) * 100; + const formattedPercentage = percentageThrown.toFixed(2); + results.push(formattedPercentage); + } + return results; } @@ -41,6 +52,11 @@ function main() { // [ '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 size of sampleSizes) { + const result = runExperiment(size); + //console.log(`Result of experiment: [${result.join(', ')}]. Sample size: ${size}.`) + console.log(`[${result.join(', ')}] ${size}.`) + } } main(); From a69a7129c6f6b0d975745a81408cf56d885470e5 Mon Sep 17 00:00:00 2001 From: Hanna Date: Sat, 4 May 2024 14:48:23 +0200 Subject: [PATCH 3/4] prep exercise week 3: done --- .../1-hyf-program/1-find-mentors.js | 27 ++++++++++++++--- .../1-hyf-program/2-class-list.js | 30 ++++++++++++++++--- Week3/prep-exercises/1-hyf-program/hyf.js | 1 + 3 files changed, 50 insertions(+), 8 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..3a3330b 100644 --- a/Week3/prep-exercises/1-hyf-program/1-find-mentors.js +++ b/Week3/prep-exercises/1-hyf-program/1-find-mentors.js @@ -1,3 +1,4 @@ +//Week3/prep-exercises/1-hyf-program/1-find-mentors.js import { modules, students, mentors, classes } from "./hyf.js"; /** @@ -8,10 +9,15 @@ import { modules, students, mentors, classes } from "./hyf.js"; * ['John', 'Mary'] */ const possibleMentorsForModule = (moduleName) => { - // TODO complete this function + return mentors.reduce((newArray, mentor) => { + if (mentor.canTeach.includes(moduleName)) { + newArray.push(mentor.name); + } + return newArray; // returns array on each reduce iteration + }, []); // has an array output }; // 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 +25,21 @@ const possibleMentorsForModule = (moduleName) => { * * It should return a single name. */ + +/** Helper function `getRandomIndex` to generate a random integer between 0 and specified max value + * + * @param {number} max - an upper limit for random number generation, exclusive + * @returns {number} random integer between 1 and `max-1` + */ +const getRandomIndex = max => (Math.floor(Math.random() * max)); + const findMentorForModule = (moduleName) => { - // TODO complete this function + const possibleMentors = possibleMentorsForModule(moduleName); + if (possibleMentors.length === 0) { + return `No mentors available for the module ${moduleName}` + } + const randomIndex = getRandomIndex(possibleMentors.length) + return possibleMentors[randomIndex] }; // 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..c02c54e 100644 --- a/Week3/prep-exercises/1-hyf-program/2-class-list.js +++ b/Week3/prep-exercises/1-hyf-program/2-class-list.js @@ -12,10 +12,27 @@ import { modules, students, mentors, classes } from "./hyf.js"; * [{ name: 'John', role: 'student' }, { name: 'Mary', role: 'mentor' }] */ const getPeopleOfClass = (className) => { - // TODO complete this function + //Check if the class exists in classes object + const classInfo = classes.find(c => c.name === className); + if (!classInfo) { + return []; + } + + //Get the students info + const classStudents = students + .filter(student => student.class ===className) + .map(student => ({name: student.name, role: 'student'})); + + //Get the mentors info + const currentModule = classInfo.currentModule; + const classMentors = mentors + .filter(mentor => mentor.nowTeaching ===currentModule) + .map(mentor => ({name: mentor.name, role: 'mentor'})); + + return [...classStudents, ...classMentors]; }; // 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 +47,12 @@ const getPeopleOfClass = (className) => { * } */ const getActiveClasses = () => { - // TODO complete this function + return classes.reduce((classObj, c) => { + if (c.active) { + classObj[c.name] = getPeopleOfClass(c.name); + } + return classObj; + }, {}) }; // 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..b8da0d1 100644 --- a/Week3/prep-exercises/1-hyf-program/hyf.js +++ b/Week3/prep-exercises/1-hyf-program/hyf.js @@ -1,3 +1,4 @@ +//Week3/prep-exercises/1-hyf-program/hyf.js export const modules = [ { name: "html-css", displayName: "HTML/CSS" }, { name: "javascript", displayName: "JavaScript" }, From 5e50e0e189f8960acd1846559b7a98fa8b6d87c9 Mon Sep 17 00:00:00 2001 From: Hanna Date: Sat, 11 May 2024 16:10:44 +0200 Subject: [PATCH 4/4] prep exercise week 4: done --- Week4/prep-exercises/1-wallet/ex2-classes.js | 21 +++++++++++++++++++ Week4/prep-exercises/1-wallet/ex3-object.js | 16 ++++++++++++++ .../1-wallet/ex4-object-shared-methods.js | 15 +++++++++++++ .../prep-exercises/1-wallet/ex5-prototype.js | 17 +++++++++++++++ 4 files changed, 69 insertions(+) diff --git a/Week4/prep-exercises/1-wallet/ex2-classes.js b/Week4/prep-exercises/1-wallet/ex2-classes.js index f016137..570fd17 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() { diff --git a/Week4/prep-exercises/1-wallet/ex3-object.js b/Week4/prep-exercises/1-wallet/ex3-object.js index e94faac..46fa5f4 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; + } }; } 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..cca1140 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, diff --git a/Week4/prep-exercises/1-wallet/ex5-prototype.js b/Week4/prep-exercises/1-wallet/ex5-prototype.js index 7cba410..a7b5de3 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);