Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

APIs week1 #4

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
29 changes: 18 additions & 11 deletions 3-UsingAPIs/Week1/homework/ex1-johnWho.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,28 @@ 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
const getAnonName = (firstName, callback) => {
setTimeout(() => {
if (!firstName) {
callback(new Error("You didn't pass in a first name!"));
return;
}

const fullName = `${firstName} Doe`;
const getAnonName = (firstName) => {
const anonName = new Promise((resolve, reject) => {
setTimeout(() => {
if (firstName) {
resolve(`${firstName} Doe`);
} else {
reject(new Error("You didn't pass in a first name!"));
}
}, 1000);
});
return anonName;
};

callback(fullName);
}, 1000);
const handleSuccess = (resolvedValue) => {
console.log(resolvedValue);
};
const handleFailure = (rejectValue) => {
console.log(rejectValue);
};

getAnonName('John', console.log);
getAnonName('John').then(handleSuccess).catch(handleFailure);

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
module.exports = getAnonName;
11 changes: 9 additions & 2 deletions 3-UsingAPIs/Week1/homework/ex2-checkDoubleDigits.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,15 @@ 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.
------------------------------------------------------------------------------*/
function checkDoubleDigits(/* TODO add parameter(s) here */) {
// TODO complete this function
function checkDoubleDigits(number) {
const checkNumber = new Promise((resolve, reject) => {
if (number >= 10 && number <= 99) {
resolve('This is double digit number!');
} else {
reject(new Error(`Expected a double digit number but got ${number}`));
}
});
return checkNumber;
}

checkDoubleDigits(11) // should resolve

Choose a reason for hiding this comment

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

👍

Expand Down
69 changes: 30 additions & 39 deletions 3-UsingAPIs/Week1/homework/ex3-rollDice.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,47 +9,38 @@
explanation? Add your answer as a comment to be bottom of the file.
------------------------------------------------------------------------------*/

// TODO Remove callback and return a promise
function rollDice(callback) {
// Compute a random number of rolls (3-10) that the dice MUST complete
const randomRollsToDo = Math.floor(Math.random() * 8) + 3;
console.log(`Dice scheduled for ${randomRollsToDo} rolls...`);

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

// Use callback to notify that the dice rolled off the table after 6 rolls
if (roll > 6) {
// TODO replace "error" callback
callback(new Error('Oops... Dice rolled off the table.'));
}

// Use callback to communicate the final dice 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 rollDice() {
const rollPromise = new Promise((resolve, reject) => {
// Compute a random number of rolls (3-10) that the dice MUST complete
const randomRollsToDo = Math.floor(Math.random() * 8) + 3;

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

if (roll > 6) {
reject(new Error('Oops... Dice rolled off the table.'));
}
if (roll === randomRollsToDo) {
resolve(`Success! Dice settled on ${value}.`);
}
if (roll < randomRollsToDo) {
setTimeout(() => rollOnce(roll + 1), 500);
}
};
// Start the initial roll
rollOnce(1);
});
return rollPromise;
}

// TODO Refactor to use promise
rollDice((error, value) => {
if (error !== null) {
console.log(error.message);
} else {
console.log(`Success! Dice settled on ${value}.`);
}
});
rollDice()
.then((resolveValue) => console.log(resolveValue))
.catch((rejectValue) => console.log(rejectValue.message));

// It looks like the promise gives the value (reject or resolve) immediately after
// the first case (rejection or resolving) happen and doesn't change this value anymore.

Choose a reason for hiding this comment

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

Yes, that is correct. Once a promise is 'settled' (i.e., resolved or rejected) its outcome can no longer be changed. Promises are deliberately designed to work that way.

// ! Do not change or remove the code below
module.exports = rollDice;
13 changes: 11 additions & 2 deletions 3-UsingAPIs/Week1/homework/ex4-pokerDiceAll.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,21 @@ const rollDice = require('../../helpers/pokerDiceRoller');
function rollTheDices() {
// TODO Refactor this function
const dices = [1, 2, 3, 4, 5];
return rollDice(1);
const resultPromises = [];
dices.forEach((dice) => {
resultPromises.push(rollDice(dice));
});
return resultPromises;

Choose a reason for hiding this comment

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

Can you try to use .map() here instead of .forEach()? Map dice number to promises? And then return the return the result of Promise.all() (itself a promise) as the return value of this function. With those changes, you do not need to modify line 30 from the way it was.

}

rollTheDices()
Promise.all(rollTheDices())
.then((results) => console.log('Resolved!', results))
.catch((error) => console.log('Rejected!', error.message));

Choose a reason for hiding this comment

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

Yes!

//1. Dices that have not yet finished their roll continue to do so because reject() doesn't mean 'return'.
//2. There only a single call to either .then() or .catch() despite resolve() and/or reject() being called more than once
//because .then() or .catch() can be called only ones. But I'm not sure :)

Choose a reason for hiding this comment

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

If a promise becomes settled it must have either been resolved or rejected. It can only be resolved or rejected once. Therefore .then() or .catch() is called only once here. Additional calls to resolve() and reject() have no effect after that any more.

//3. We get "Rejected! Dice ... rolled off the table." only once even if several dices rolled off the table
//because if one of the promises is rejected the promise returned by Promise.all() is rejected.
// ! Do not change or remove the code below
module.export = rollTheDices;
31 changes: 31 additions & 0 deletions 3-UsingAPIs/Week1/homework/ex5-rollDiceChain.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Challenge: throw five dices in sequence
const rollDice = require('../../helpers/pokerDiceRoller');
function rollTheDices() {
const results = [];

rollDice(1)
.then((value) => {
results.push(value);
return rollDice(2);
})
.then((value) => {
results.push(value);
return rollDice(3);
})
.then((value) => {
results.push(value);
return rollDice(4);
})
.then((value) => {
results.push(value);
return rollDice(5);
})
.then((value) => {
results.push(value);
console.log('Resolved!', results);
})
.catch((error) => console.log('Rejected!', error.message));
}
rollTheDices();
// ! Do not change or remove the code below
module.exports = rollTheDices;

Choose a reason for hiding this comment

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

Your solution should work fine, but if you would like to test your understanding of using functions-returning-a-function, can you fill in the dots in this code snippet?

function rollTheDices() {
  const results = [];

  const pushAndRoll = (dice) => (value) => {
    ...
  };

  rollDice(1)
    .then(pushAndRoll(2))
    .then(pushAndRoll(3))
    .then(pushAndRoll(4))
    .then(pushAndRoll(5))
    .then((value) => {
      results.push(value);
      console.log('Resolved!', results);
    })
    .catch((error) => console.log('Rejected!', error.message));
}

Copy link
Owner Author

Choose a reason for hiding this comment

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

I've doen it. Is it correct?

Choose a reason for hiding this comment

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

It looks correct and I assume it also works as expected. But that is something for you to confirm.

Choose a reason for hiding this comment

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

So we discussed this code as an alternative to repeating the same code for each .then(). Whether you prefer this DRY version over the repetitive version is a matter of personal choice.

1 change: 1 addition & 0 deletions 3-UsingAPIs/Week1/test-reports/ex1-johnWho.pass.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
All tests passed
1 change: 0 additions & 1 deletion 3-UsingAPIs/Week1/test-reports/ex1-johnWho.todo.txt

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
All tests passed

This file was deleted.

1 change: 1 addition & 0 deletions 3-UsingAPIs/Week1/test-reports/ex3-rollDice.pass.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
All tests passed
1 change: 0 additions & 1 deletion 3-UsingAPIs/Week1/test-reports/ex3-rollDice.todo.txt

This file was deleted.

1 change: 1 addition & 0 deletions 3-UsingAPIs/Week1/test-reports/ex4-pokerDiceAll.pass.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
All tests passed
1 change: 0 additions & 1 deletion 3-UsingAPIs/Week1/test-reports/ex4-pokerDiceAll.todo.txt

This file was deleted.

1 change: 1 addition & 0 deletions 3-UsingAPIs/Week1/test-reports/ex5-rollDiceChain.pass.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
All tests passed
71 changes: 71 additions & 0 deletions sysinfo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
{
"node": "v14.15.4",
"system": {
"manufacturer": "Acer",
"model": "Aspire ES1-331"
},
"cpu": {
"manufacturer": "Intel®",
"brand": "Pentium® N3700",
"speed": 1.6
},
"memory": "8 GB",
"osInfo": {
"platform": "win32",
"distro": "�������� Windows 10 ������� ��� ������ �몠",
"release": "10.0.19042"
},
"blockDevices": [
{
"name": "C:",
"size": "499 GB",
"fsType": "ntfs",
"physical": "Local"
}
],
"vscodeInfo": {
"version": "1.54.3",
"extensions": [
"aaron-bond.better-comments",
"bierner.github-markdown-preview",
"bierner.markdown-checkbox",
"bierner.markdown-emoji",
"bierner.markdown-preview-github-styles",
"bierner.markdown-yaml-preamble",
"CoenraadS.bracket-pair-colorizer",
"CoenraadS.bracket-pair-colorizer-2",
"DavidAnson.vscode-markdownlint",
"dbaeumer.vscode-eslint",
"eamodio.gitlens",
"esbenp.prettier-vscode",
"evgeniypeshkov.syntax-highlighter",
"formulahendry.code-runner",
"hdg.live-html-previewer",
"ritwickdey.LiveServer",
"streetsidesoftware.code-spell-checker",
"techer.open-in-browser",
"vsls-contrib.codetour"
],
"userSettings": {
"editor.detectIndentation": false,
"editor.formatOnSave": true,
"editor.minimap.enabled": false,
"editor.renderIndentGuides": true,
"editor.tabSize": 2,
"editor.codeActionsOnSave": {
"source.fixAll": true
},
"eslint.autoFixOnSave": true,
"files.autoSave": "onFocusChange",
"prettier.singleQuote": true,
"prettier.trailingComma": "all",
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",
"workbench.colorTheme": "Visual Studio Light",
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"liveServer.settings.donotShowInfoMsg": true,
"window.zoomLevel": 1
}
}
}
61 changes: 61 additions & 0 deletions [email protected]
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
2021-03-19 01:33:45 info: ---------------------------------------
2021-03-19 01:33:45 info: >>> Running Unit Test `ex1-johnWho` <<<
2021-03-19 01:33:45 info: ---------------------------------------
2021-03-19 01:34:42 error: *** Unit Test Error Report ***

- getAnonName should return a resolved promise when called with a string argument
Expected: John Doe
Received: John

2021-03-19 01:36:22 info: ---------------------------------------
2021-03-19 01:36:22 info: >>> Running Unit Test `ex1-johnWho` <<<
2021-03-19 01:36:22 info: ---------------------------------------
2021-03-19 01:36:40 info: All unit tests passed.
2021-03-19 01:36:52 info: All steps were completed successfully
2021-03-19 02:47:53 info: -------------------------------------------------
2021-03-19 02:47:53 info: >>> Running Unit Test `ex2-checkDoubleDigits` <<<
2021-03-19 02:47:53 info: -------------------------------------------------
2021-03-19 02:48:58 info: All unit tests passed.
2021-03-19 02:49:18 info: All steps were completed successfully
2021-03-19 06:36:05 info: ----------------------------------------
2021-03-19 06:36:05 info: >>> Running Unit Test `ex3-rollDice` <<<
2021-03-19 06:36:05 info: ----------------------------------------
2021-03-19 06:36:23 info: All unit tests passed.
2021-03-19 06:36:38 info: All steps were completed successfully
2021-03-19 07:37:15 info: ----------------------------------------
2021-03-19 07:37:15 info: >>> Running Unit Test `ex3-rollDice` <<<
2021-03-19 07:37:15 info: ----------------------------------------
2021-03-19 07:37:31 info: All unit tests passed.
2021-03-19 07:37:44 info: All steps were completed successfully
2021-03-20 02:01:16 info: ----------------------------------------
2021-03-20 02:01:16 info: >>> Running Unit Test `ex3-rollDice` <<<
2021-03-20 02:01:16 info: ----------------------------------------
2021-03-20 02:01:51 info: All unit tests passed.
2021-03-20 02:01:57 error: *** ESLint Report ***

ex3-rollDice.js
15:5 warning Remove commented-out code hyf/no-commented-out-code

✖ 1 problem (0 errors, 1 warning)


2021-03-20 02:03:47 info: ----------------------------------------
2021-03-20 02:03:47 info: >>> Running Unit Test `ex3-rollDice` <<<
2021-03-20 02:03:47 info: ----------------------------------------
2021-03-20 02:04:03 info: All unit tests passed.
2021-03-20 02:04:17 info: All steps were completed successfully
2021-03-20 02:06:17 info: ----------------------------------------
2021-03-20 02:06:17 info: >>> Running Unit Test `ex3-rollDice` <<<
2021-03-20 02:06:17 info: ----------------------------------------
2021-03-20 02:06:33 info: All unit tests passed.
2021-03-20 02:06:54 info: All steps were completed successfully
2021-03-20 03:55:45 info: --------------------------------------------
2021-03-20 03:55:45 info: >>> Running Unit Test `ex4-pokerDiceAll` <<<
2021-03-20 03:55:45 info: --------------------------------------------
2021-03-20 03:56:02 info: All unit tests passed.
2021-03-20 03:56:15 info: All steps were completed successfully
2021-03-22 02:12:27 info: ---------------------------------------------
2021-03-22 02:12:27 info: >>> Running Unit Test `ex5-rollDiceChain` <<<
2021-03-22 02:12:27 info: ---------------------------------------------
2021-03-22 02:12:27 warn: A unit test file was not provided.
2021-03-22 02:12:46 info: All steps were completed successfully