diff --git a/3-UsingAPIs/Week1/assignment/ex1-johnWho.js b/3-UsingAPIs/Week1/assignment/ex1-johnWho.js index 5851c8c4f..7683823c0 100644 --- a/3-UsingAPIs/Week1/assignment/ex1-johnWho.js +++ b/3-UsingAPIs/Week1/assignment/ex1-johnWho.js @@ -7,24 +7,27 @@ Rewrite this function, but replace the callback syntax with the Promise syntax: - If the Promise `rejects`, pass an error as the argument to reject with: "You didn't pass in a first name!" ------------------------------------------------------------------------------*/ -// TODO see above -export const getAnonName = (firstName, callback) => { - setTimeout(() => { - if (!firstName) { - callback(new Error("You didn't pass in a first name!")); - return; - } +export const getAnonName = (firstName) => { + return new Promise((resolve, reject) => { + setTimeout(() => { + if (!firstName) { + reject(new Error("You didn't pass in a first name!")); + return; + } - const fullName = `${firstName} Doe`; - - callback(fullName); - }, 1000); + const fullName = `${firstName} Doe`; + resolve(fullName); + }, 1000); + }); }; function main() { - getAnonName('John', console.log); + getAnonName('John') + .then(console.log) + .catch(console.error); } + // ! Do not change or remove the code below if (process.env.NODE_ENV !== 'test') { main(); diff --git a/3-UsingAPIs/Week1/assignment/ex2-checkDoubleDigits.js b/3-UsingAPIs/Week1/assignment/ex2-checkDoubleDigits.js index 4b31d1927..1682da6d5 100644 --- a/3-UsingAPIs/Week1/assignment/ex2-checkDoubleDigits.js +++ b/3-UsingAPIs/Week1/assignment/ex2-checkDoubleDigits.js @@ -11,8 +11,14 @@ Complete the function called `checkDoubleDigits` such that: "Expected a double digit number but got `number`", where `number` is the number that was passed as an argument. ------------------------------------------------------------------------------*/ -export function checkDoubleDigits(/* TODO add parameter(s) here */) { - // TODO complete this function +export function checkDoubleDigits(number) { + return new Promise((resolve, reject) => { + if (number >= 10 && number <= 99) { + resolve("This is a double digit number!"); + } else { + reject(new Error(`Expected a double digit number but got ${number}`)); + } + }); } function main() { diff --git a/3-UsingAPIs/Week1/assignment/ex3-rollDie.js b/3-UsingAPIs/Week1/assignment/ex3-rollDie.js index 7e4b77888..b1043951c 100644 --- a/3-UsingAPIs/Week1/assignment/ex3-rollDie.js +++ b/3-UsingAPIs/Week1/assignment/ex3-rollDie.js @@ -10,8 +10,9 @@ Full description at: https://github.com/HackYourFuture/Assignments/tree/main/3-U explanation? Add your answer as a comment to be bottom of the file. ------------------------------------------------------------------------------*/ -// TODO Remove callback and return a promise -export function rollDie(callback) { +export function rollDie() { + return new Promise((resolve, reject) => { + // Compute a random number of rolls (3-10) that the die MUST complete const randomRollsToDo = Math.floor(Math.random() * 8) + 3; console.log(`Die scheduled for ${randomRollsToDo} rolls...`); @@ -23,35 +24,31 @@ export function rollDie(callback) { // Use callback to notify that the die rolled off the table after 6 rolls if (roll > 6) { - // TODO replace "error" callback - callback(new Error('Oops... Die rolled off the table.')); + reject(new Error('Oops... Die rolled off the table.')); + return; } // Use callback to communicate the final die value once finished rolling if (roll === randomRollsToDo) { - // TODO replace "success" callback - callback(null, value); + resolve(value); + return; } // Schedule the next roll todo until no more rolls to do - if (roll < randomRollsToDo) { + if (roll < randomRollsToDo) { setTimeout(() => rollOnce(roll + 1), 500); } }; // Start the initial roll rollOnce(1); + }); } function main() { - // TODO Refactor to use promise - rollDie((error, value) => { - if (error !== null) { - console.log(error.message); - } else { - console.log(`Success! Die settled on ${value}.`); - } - }); + rollDie() + .then(value => console.log(`Success! Die settled on ${value}.`)) + .catch(error => console.log(error.message)); } // ! Do not change or remove the code below @@ -59,4 +56,15 @@ if (process.env.NODE_ENV !== 'test') { main(); } -// TODO Replace this comment by your explanation that was asked for in the assignment description. +/*Explanation: + +Before, using callbacks caused a problem because when the die rolled off the table or finished rolling, the messages could happen in a random order + +Now, using a Promise + +1. We call `resolve()` when the die finishes rolling successfully. +2. We call `reject()` if the die rolls off the table (more than 6 rolls) + +Promises make sure only one thing happens: either success or error. We can handle it easily with `.then()` for success and `.catch()` for errors. + +Because of this, the previous problem does not happen anymore, and everything runs in a clear predictable order */ \ No newline at end of file diff --git a/3-UsingAPIs/Week1/assignment/ex4-pokerDiceAll.js b/3-UsingAPIs/Week1/assignment/ex4-pokerDiceAll.js index d88cd71d2..4919deb43 100644 --- a/3-UsingAPIs/Week1/assignment/ex4-pokerDiceAll.js +++ b/3-UsingAPIs/Week1/assignment/ex4-pokerDiceAll.js @@ -27,11 +27,12 @@ exercise file. import { rollDie } from '../../helpers/pokerDiceRoller.js'; export function rollDice() { - // TODO Refactor this function const dice = [1, 2, 3, 4, 5]; - return rollDie(1); -} + const dicePromises = dice.map(() => rollDie()); + return Promise.all(dicePromises); + } + function main() { rollDice() .then((results) => console.log('Resolved!', results)) @@ -43,4 +44,14 @@ if (process.env.NODE_ENV !== 'test') { main(); } -// TODO Replace this comment by your explanation that was asked for in the assignment description. +/* +Explanation: + +We throw five dice at the same time using Promise.all. Each die is like a separate promise. +- If all dice finish rolling without problems, we get an array with all the results. +- If one die falls off the table, Promise.all stops and gives an error. + +Even if one die fails, the other dice keep rolling. +This happens because each die rolls in its own process, and Promise.all cannot stop them once they started. +It only stops the main result from coming, but the dice themselves keep going until they finish. +*/ diff --git a/3-UsingAPIs/Week1/assignment/ex5-pokerDiceChain.js b/3-UsingAPIs/Week1/assignment/ex5-pokerDiceChain.js index 5b1394b84..e2ebb1923 100644 --- a/3-UsingAPIs/Week1/assignment/ex5-pokerDiceChain.js +++ b/3-UsingAPIs/Week1/assignment/ex5-pokerDiceChain.js @@ -10,6 +10,7 @@ To throw the dice sequentially we will be using a _promise chain_. Your job is to expand the given promise chain to include five dice. ------------------------------------------------------------------------------*/ + // The line below makes the rollDie() function available to this file. // Do not change or remove it. import { rollDie } from '../../helpers/pokerDiceRoller.js'; @@ -17,15 +18,26 @@ import { rollDie } from '../../helpers/pokerDiceRoller.js'; export function rollDice() { const results = []; - // TODO: expand the chain to include five dice return rollDie(1) .then((value) => { results.push(value); return rollDie(2); }) + .then((value) => { + results.push(value); + return rollDie(3); + }) + .then((value) => { + results.push(value); + return rollDie(4); + }) .then((value) => { results.push(value); - return results; + return rollDie(5); + }) + .then((value) => { + results.push(value); + return results; // Return all results at the end }); } @@ -39,3 +51,13 @@ function main() { if (process.env.NODE_ENV !== 'test') { main(); } +/* +Explanation: + +We throw five dice one by one, waiting for each to finish before throwing the next. +- If a die finishes normally, its value is added to the results array. +- If a die rolls off the table, the chain stops immediately and the error is caught. + +This is different from Promise.all(), because here each die waits for the previous one. +Even though a die falls off, any dice that haven't started yet never roll. +*/ \ No newline at end of file diff --git a/README.md b/README.md index d457d2828..5e5773557 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ We highly recommend that you go through this README in detail before starting to > > This will ensure that the line endings for text files are compatible with those used on MacOS and Linux-based computers. -1. Fork the `HackYourAssignment/Assignments-CohortXX` repository to your own GitHub account. +1. Fork the `HackYourAssignment/JavaScript-CohortXX` repository to your own GitHub account. 2. Clone the fork to your local computer. 3. Open the root folder of the repository in VSCode. 4. When invited to do so, please install the recommended VSCode extensions. @@ -24,7 +24,7 @@ We highly recommend that you go through this README in detail before starting to 10. Fix any reported issues and rerun the test. Repeat until all issues are fixed. 11. When all assignments are done, commit all changed files. This includes the modified exercises, the generated test summary (`TEST_SUMMARY.md`) and test reports (`EXERCISE_NAME.report.txt`). 12. Push the changes to your fork. -13. Create a pull request against the `main` branch of the `HackYourAssignment/Assignments-CohortXX` repository. For the title of your pull request use the same format as the branch name, e.g.: `YOUR_NAME-w2-JavaScript`. +13. Create a pull request against the `main` branch of the `HackYourAssignment/JavaScript-CohortXX` repository. For the title of your pull request use the same format as the branch name, e.g.: `YOUR_NAME-w2-JavaScript`. Repeat steps 6-13 for each week. For subsequent weeks the mandated branch names are: @@ -39,7 +39,7 @@ For more information how to hand in your weekly assignments please refer to the Throughout your [HYF journey](https://github.com/HackYourFuture/curriculum) you will be asked to do certain exercises. This repository contains all of these exercises for the JavaScript modules (JavaScript, Browsers, UsingAPIs). The module repositories will tell you how to hand in the assignment, the curriculum will indicate what week you will need to do. -> Note that a fork of this repository will be created on the [HackYourAssignment](https://github.com/HackYourAssignment) GitHub account specifically for your cohort. The name of the repository will have the format `Assignments-cohortXX` where `XX` is your cohort number, +> Note that a fork of this repository will be created on the [HackYourAssignment](https://github.com/HackYourAssignment) GitHub account specifically for your cohort. The name of the repository will have the format `JavaScript-cohortXX` where `XX` is your cohort number, ## Installation @@ -64,9 +64,9 @@ From the command line, while inside the `Assignments-cohortXX` folder, you can u code . ``` -> When working on your assignments it is strongly recommended to always open the `Assignments-cohortXX` folder in VSCode rather than one of its sub-folders. This gives VSCode and all its extensions the full view on the repository for the best overall developer experience. +> When working on your assignments it is strongly recommended to always open the `JavaScript-cohortXX` folder in VSCode rather than one of its sub-folders. This gives VSCode and all its extensions the full view on the repository for the best overall developer experience. > -> Note that the name of the folder opened in VSCode can always be found in the `EXPLORER` panel ( `ASSIGNMENTS_COHORT49` in the picture below): +> Note that the name of the folder opened in VSCode can always be found in the `EXPLORER` panel ( `ASSIGNMENT_COHORT49` in the picture below): > > ![folder-name](./assets/folder-name.png)