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

Solution/RenatoMonroy #22

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
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
63 changes: 63 additions & 0 deletions 1-callbacks/other-solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
INSTRUCTIONS

1. create an array that contains 5 names, include 1 or more of the allowed usernames located in validate-user.js
2. iterate the array, keep an eye on performance, and validate every username with the function exported in validate-user.js
3. process and format every result, so that the program console.log the success results in a group, and the failure results in a group

Example:

Success

id:1
name: John

id:2
name: Mary

Failure

User Michael not allowed
User Benjamin not allowed

4. if you want to challenge yourself, add the needed logic so the program can read the array of names from the terminal
** check about node.js process.argv **

Example:

node solution.js name1,name2,name3, or
node solution.js name1 name2 name3

5. another challenge is: after you solve the challenge using callback style, in another file promisify the callback and solve it again
** give a look to node.js util.promisify, avoid to alter the validate-user.file **
*/

/* with steps 4 and 5 */
const process = require('node:process');
const util = require('node:util');
const validateName = require('./validate-user');

/*
NOTE: I've tried a lot of ways to make use of the promise properly since the provided
function is tricky, I made use of the error handler to print it as desired because that Error object has to be used...
I didn't commit all the tries because that would be junk so I stayed with this one, looks good so far.
*/

function solution() {
// get parameters from console
const names = process.argv.filter((item, index) => index > 1);
// using promisify
const validateAsync = util.promisify(validateName);

// Logging the results
console.log('Success');
for (const name of names) {
validateAsync(name, (...params) => {
if (params.length > 1) console.log(`\nid: ${params[1].id}\nname: ${params[1].name}\n`)
else throw new Error(params[0].message);
}).catch(error => setTimeout(() => console.error(error.message), 350));
}
setTimeout(() => console.log('Failure\n'), 350);
}
Comment on lines +55 to +61
Copy link

Choose a reason for hiding this comment

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

since we've promised the validateName function, we could use promises or async/await on the validateAsync instead of a callback


solution()
23 changes: 20 additions & 3 deletions 1-callbacks/solution.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,32 @@ node solution.js name1 name2 name3
5. another challenge is: after you solve the challenge using callback style, in another file promisify the callback and solve it again
** give a look to node.js util.promisify, avoid to alter the validate-user.file **
*/
const validateName = require('./validate-user');

function solution() {
// YOUR SOLUTION GOES HERE

// you get your 5 names here
// Array of names with 2 matches
const names = ['Quebec', 'Rasmus', 'Mary', 'Zeada', 'Richard'];

// iterate the names array and validate them with the method
console.log('Success');
for (const name of names) {
Copy link

Choose a reason for hiding this comment

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

just to add readability, always separate blocks of code like loops, conditionals, etc using a line break at the start of that block

validateName(name, callback);
}

setTimeout(() => {
console.log('Failure\n');
}, 350);

// log the final result
function callback(...params) {
if (params.length > 1)
console.log(`\nid: ${params[1].id}\nname: ${params[1].name}\n`);
else {
setTimeout(() => {
console.log(params[0].message);
}, 400);
}
}
Comment on lines +51 to +59
Copy link

Choose a reason for hiding this comment

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

we must keep the standards, if we know that the first argument is the error, and the second argument is the data, we must name these parameters in this way, so it will help other devs to understand your code easily

}

solution()
Expand Down
37 changes: 28 additions & 9 deletions 2-promises/solution.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,35 @@ const id = yourRandomMethod() //third run
7. log the resultant fullname, or the error, at the end
*/

function solution() {
// YOUR SOLUTION GOES HERE

// You generate your id value here

// You call the lastnames method with your id
const process = require('node:process')
const firstnames = require('./firstnames');
const lastnames = require('./lastnames');

// You call the firstname method

// You log the fullname, or error, here
function solution() {
const id = randomId();

console.log(`ID: ${id}`);
// Lastname callback
lastnames(id).then(lname => {
// For the sake of printing it same as the example I used stdout.write
process.stdout.write(`${lname}, `);

// Firstname callback
firstnames(lname).then(fname => {
process.stdout.write(`${fname}\n`);
Comment on lines +38 to +42
Copy link

Choose a reason for hiding this comment

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

since we are returning both lname and name together, we could just use a process.stdout.write in the second then method

}).catch(error => console.log(error.message));

}).catch(error => console.log(error.message));

// NOTE: The randomId() function tends to be very.. unlucky. Please spam it until you see all the cases.
// randomizing logic that provides an id for lastnames method
function randomId() {
const desire = [1, -1];
const choice = Math.floor(Math.random() * desire.length);
return (Math.floor(Math.random() * 2)) ?
Copy link

Choose a reason for hiding this comment

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

the same recommendation about readability for a return

Math.floor(Math.random() * 101) * desire[choice] :
Math.floor(Math.random() * 101) * desire[choice] + desire.toString(); // whatever different to a positive integer
}
}

solution()
101 changes: 99 additions & 2 deletions 3-async-await/solution.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,114 @@ Example:
8. add any needed adjustment to solution() function
9. as extra challenge: add Promise.race() and Promise.any(), and try to get the idea of what happens
*/
const prices = require('./prices');
const products = require('./products');

function solution() {
async function solution() {
// YOUR SOLUTION GOES HERE

// You generate your id value here
// NOTE : from what I tested, if you want to display the case where all 4 cases fail please assign 48 to id.
const id = randomId();
console.log(`The ID generated for this run is ${id}\n`);



// You use Promise.all() here
console.log('\tUsing Promise.all\n');
try {
const allPromises = await Promise.all([
prices(id),
products(id),
]);

console.log({ id, product: allPromises[1], price: allPromises[0] });

} catch (error) {
console.log('Entered Promise.all catch block');
console.error(error.message);
}



// You use Promise.allSettled() here
console.log('\n\tUsing Promise.allSettled\n');
try {
const promisesSettled = await Promise.allSettled([
prices(id),
products(id),
]);

const promisesFulfilled = promisesSettled.filter(promise => promise.status === 'fulfilled').map(result => result.value);
const promisesRejected = promisesSettled.filter(promise => promise.status === 'rejected').map(result => result.reason.message);

if (promisesRejected.length) throw new Error(promisesRejected);

// Log the results, or errors, here
console.log({ id, product: promisesFulfilled[1], price: promisesFulfilled[0] });

} catch (error) {
/* NOTE : I've been trying to do proper error handling with all the promises but I had one struggle
Copy link

Choose a reason for hiding this comment

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

Keep in mind the difference between Promise.all and Promise.allSettled is that in the first an error could be thrown any moment so we should use a try/catch. But in the second case, it stores the results on each promise, so the error is stored too. It seems to me that line 64 is enough

// error.message allways gets a string "${error.name}: ${error.message},${error.name}: ${error.message}"
// and I haven't found a proper way to recieve the Error object itself, catch always parses it into a single string.
// so this is my best try to get all the errors printed in a good format.
*/
console.log('Entered Promise.allSettled catch block');
const msg = [error.message].join(' ').split(',');
msg.forEach(err => console.error(err));
}




// You use Promise.any() here
console.log('\n\tUsing Promise.any\n');
try {
const anyPromise = await Promise.any([
prices(id),
products(id),
]);

if (anyPromise.status === 'rejected') throw new Error(anyPromise);

// Log the results, or errors, here
if (typeof anyPromise === 'string')
console.log({ id, product: anyPromise, price: 'Not determined by any' });
else if (typeof anyPromise === 'number')
console.log({ id, product: 'Not determined by any', price: anyPromise });

} catch (error) {
console.log('Entered Promise.any catch block');
console.error(error.message);
}




// You use Promise.race() here
console.log('\n\tUsing Promise.race\n');
try {
const promiseRace = await Promise.race([
prices(id),
products(id),
]);

// Log the results, or errors, here
if (typeof promiseRace === 'string')
console.log({ id, product: promiseRace, price: 'Not determined by race' });
else if (typeof promiseRace === 'number')
console.log({ id, product: 'Not determined by race', price: promiseRace });

} catch (error) {
console.log('Entered Promise.race catch block');
console.error(error.message);
}



// Log the results, or errors, here
function randomId() {
return Number(String(Date.now()).slice(-2, this.lenght));
}
}

solution()