Skip to content
Closed
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
47 changes: 16 additions & 31 deletions 3-UsingAPIs/Week1/assignment/ex1-johnWho.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,16 @@
/*------------------------------------------------------------------------------
Full description at: https://github.com/HackYourFuture/Assignments/tree/main/3-UsingAPIs/Week1#exercise-1-john-who

Rewrite this function, but replace the callback syntax with the Promise syntax:
- Have the `getAnonName` function return a `new Promise`.
- If the Promise `resolves`, pass the full name as an argument to resolve with.
- 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;
}

const fullName = `${firstName} Doe`;

callback(fullName);
}, 1000);
};

function main() {
getAnonName('John', console.log);
}

// ! Do not change or remove the code below
if (process.env.NODE_ENV !== 'test') {
main();
}
export const getAnonName = (firstName) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (firstName) {
resolve(`${firstName} Doe`);
} else {
reject(new Error("You didn't pass in a first name!"));
}
}, 1000);
});
};

// ! Do not change or remove the code below
if (process.env.NODE_ENV !== 'test') {
main();
}
71 changes: 32 additions & 39 deletions 3-UsingAPIs/Week1/assignment/ex2-checkDoubleDigits.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,32 @@
/*------------------------------------------------------------------------------
Full description at: https://github.com/HackYourFuture/Assignments/tree/main/3-UsingAPIs/Week1#exercise-2-is-it-a-double-digit-number

Complete the function called `checkDoubleDigits` such that:

- It takes one argument: a number
- It returns a `new Promise`.
- If the number between 10 and 99 it should resolve to the string
"This is a double digit number!".
- For any other number it should reject with an an Error object containing:
"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
}

function main() {
checkDoubleDigits(9) // should reject
.then((message) => console.log(message))
.catch((error) => console.log(error.message));

checkDoubleDigits(10) // should resolve
.then((message) => console.log(message))
.catch((error) => console.log(error.message));

checkDoubleDigits(99) // should resolve
.then((message) => console.log(message))
.catch((error) => console.log(error.message));

checkDoubleDigits(100) // should reject
.then((message) => console.log(message))
.catch((error) => console.log(error.message));
}

// ! Do not change or remove the code below
if (process.env.NODE_ENV !== 'test') {
main();
}
export function checkDoubleDigits(number) {
return new Promise((resolve, reject) => {
if (number < 100 && number > 9) {
resolve('This is a double digit number!');
} else {
reject(new Error`Expected a double digit number but got ${number}`());
}
});
}

function main() {
checkDoubleDigits(9) // should reject
.then((message) => console.log(message))
.catch((error) => console.log(error.message));

checkDoubleDigits(10) // should resolve
.then((message) => console.log(message))
.catch((error) => console.log(error.message));

checkDoubleDigits(99) // should resolve
.then((message) => console.log(message))
.catch((error) => console.log(error.message));

checkDoubleDigits(100) // should reject
.then((message) => console.log(message))
.catch((error) => console.log(error.message));
}

// ! Do not change or remove the code below
if (process.env.NODE_ENV !== 'test') {
main();
}
95 changes: 33 additions & 62 deletions 3-UsingAPIs/Week1/assignment/ex3-rollDie.js
Original file line number Diff line number Diff line change
@@ -1,62 +1,33 @@
/*------------------------------------------------------------------------------
Full description at: https://github.com/HackYourFuture/Assignments/tree/main/3-UsingAPIs/Week1#exercise-3-roll-a-die

- Run the unmodified program and confirm that problem described occurs.
- Refactor the `rollDie()` function from callback-based to returning a
promise.
- Change the calls to `callback()` to calls to `resolve()` and `reject()`.
- Refactor the code that call `rollDie()` to use the promise it returns.
- Does the problem described above still occur? If not, what would be your
explanation? Add your answer as a comment to be bottom of the file.
------------------------------------------------------------------------------*/

// TODO Remove callback and return a promise
export function rollDie(callback) {
// 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...`);

const rollOnce = (roll) => {
// Compute a random die value for the current roll
const value = Math.floor(Math.random() * 6) + 1;
console.log(`Die value is now: ${value}`);

// 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.'));
}

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

// Schedule the next roll todo until no more rolls to do
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}.`);
}
});
}

// ! 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.
export function rollDie() {
return new Promise((resolve, reject) => {
const randomRollsToDo = Math.floor(Math.random() * 8) + 3;
console.log(`Die scheduled for ${randomRollsToDo} rolls...`);

const rollOnce = (roll) => {
const value = Math.floor(Math.random() * 6) + 1;
console.log(`Die value is now: ${value}`);

if (roll > 6) {
reject(new Error('Oops... Die rolled off the table.'));
} else if (roll === randomRollsToDo) {
resolve(value);
} else if (roll < randomRollsToDo) {
setTimeout(() => rollOnce(roll + 1), 500);
}
};
rollOnce(1);
});
}

function main() {
rollDie()
.then((value) => console.log(`Success! Die settled on ${value}.`))
.catch((error) => console.log(error.message));
}

// ! 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.
70 changes: 24 additions & 46 deletions 3-UsingAPIs/Week1/assignment/ex4-pokerDiceAll.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,24 @@
/*------------------------------------------------------------------------------
Full description at: https://github.com/HackYourFuture/Assignments/tree/main/3-UsingAPIs/Week1#exercise-4-throw-the-dice-for-a-poker-dice-game

For this exercise you should do the following:
- Refactor the `rollDice()` function to throw five dice in one go, by
using `.map()` on the `dice` array to create an array of promises for use
with `Promise.all()`.
- A successful (i.e. resolved) throw should output a message similar to:
Resolved! [ 'JACK', 'QUEEN', 'QUEEN', 'NINE', 'JACK' ]
- An unsuccessful (i.e. rejected) throw should output a message similar to:
Rejected! Die 3 rolled off the table.

The provided rollDie() function logs the value of a die as it rolls,
time-stamped with the time of day (with millisecond accuracy) to the console.
Once you have successfully completed this exercise you will notice that the
intermediate messages are output in bursts of up to five at a time as the dice
finish rolling asynchronously.

You may also notice that, in the case of a rejected promise, dice that have not
yet finished their roll continue to do so.
Can you explain why? Please add your answer as a comment to the end of the
exercise file.
------------------------------------------------------------------------------*/

// 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() {
// TODO Refactor this function
const dice = [1, 2, 3, 4, 5];
return rollDie(1);
}

function main() {
rollDice()
.then((results) => console.log('Resolved!', results))
.catch((error) => console.log('Rejected!', error.message));
}

// ! 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.
import { rollDie } from '../../helpers/pokerDiceRoller.js';

export function rollDice() {
const dice = [1, 2, 3, 4, 5];

const diceThrow = dice.map((num) => {
return rollDie(num);
});

return Promise.all(diceThrow);
}

function main() {
rollDice()
.then((results) => console.log('Resolved!', results))
.catch((error) => console.log('Rejected!', error.message));
}

// ! Do not change or remove the code below
if (process.env.NODE_ENV !== 'test') {
main();
}

// ! because promises do not stop until they finish. Promise.all() stops with the first rejection or any other rejection but the promises continuo until they finished
79 changes: 38 additions & 41 deletions 3-UsingAPIs/Week1/assignment/ex5-pokerDiceChain.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,38 @@
/*------------------------------------------------------------------------------
Full description at: https://github.com/HackYourFuture/Assignments/tree/main/3-UsingAPIs/Week1#exercise-5-throw-dice-sequentially

In the previous exercise we used `Promise.all()` to throw five dice in one go.
In the current exercise we will be throwing five dice one at a time, waiting
for a die to settle before throwing the next one. Of course, we still consider
a die rolling off the table to be a showstopper.

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

function main() {
rollDice()
.then((results) => console.log('Resolved!', results))
.catch((error) => console.log('Rejected!', error.message));
}

// ! Do not change or remove the code below
if (process.env.NODE_ENV !== 'test') {
main();
}
import { rollDie } from '../../helpers/pokerDiceRoller.js';

export function rollDice() {
const results = [];

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 rollDie(5);
})
.then((value) => {
results.push(value);
return results;
});
}

function main() {
rollDice()
.then((results) => console.log('Resolved!', results))
.catch((error) => console.log('Rejected!', error.message));
}

// ! Do not change or remove the code below
if (process.env.NODE_ENV !== 'test') {
main();
}