Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 15 additions & 12 deletions 3-UsingAPIs/Week1/assignment/ex1-johnWho.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Comment on lines +10 to +21
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great job writing clean code that returns a promise, and processing resolve and reject.

};

function main() {
getAnonName('John', console.log);
getAnonName('John')
.then(console.log)
.catch(console.error);
Comment on lines +25 to +27
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good job separating the success output and the error output.

}


// ! Do not change or remove the code below
if (process.env.NODE_ENV !== 'test') {
main();
Expand Down
10 changes: 8 additions & 2 deletions 3-UsingAPIs/Week1/assignment/ex2-checkDoubleDigits.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}`));
}
});
Comment on lines +14 to +21
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good! Meets all the requirements. 👍

}

function main() {
Expand Down
40 changes: 24 additions & 16 deletions 3-UsingAPIs/Week1/assignment/ex3-rollDie.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍


// 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...`);
Expand All @@ -23,40 +24,47 @@ 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.'));
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

return;
}

// Use callback to communicate the final die value once finished rolling
if (roll === randomRollsToDo) {
// TODO replace "success" callback
callback(null, value);
resolve(value);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

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));
Comment on lines +49 to +51
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

}

// ! Do not change or remove the code below
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 */
Comment on lines +59 to +70
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

19 changes: 15 additions & 4 deletions 3-UsingAPIs/Week1/assignment/ex4-pokerDiceAll.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Comment on lines +32 to +35
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good job using Promise.all()

function main() {
rollDice()
.then((results) => console.log('Resolved!', results))
Expand All @@ -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.
*/
Comment on lines +47 to +57
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well done

26 changes: 24 additions & 2 deletions 3-UsingAPIs/Week1/assignment/ex5-pokerDiceChain.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,34 @@ 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';

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
});
}

Expand All @@ -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.
*/
Comment on lines +54 to +63
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good!

10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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:

Expand All @@ -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

Expand All @@ -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)

Expand Down