From df90094a1ef43957627bcd696edaecd901d481d0 Mon Sep 17 00:00:00 2001 From: rdev32 Date: Tue, 18 Apr 2023 15:38:17 -0500 Subject: [PATCH 1/8] feat: add callbacks implementation solution --- 1-callbacks/solution.js | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/1-callbacks/solution.js b/1-callbacks/solution.js index 654e4f5..d0cffb3 100644 --- a/1-callbacks/solution.js +++ b/1-callbacks/solution.js @@ -31,15 +31,29 @@ 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 - - // iterate the names array and validate them with the method - - // log the final result + const names = ['Quebec', 'Rasmus', 'Mary', 'Zeada', 'Richard']; + + console.log('Success'); + for (const name of names) { + validateName(name, callback); + } + + setTimeout(() => { + console.log('Failure\n'); + }, 350); + + 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); + } + } } solution() From edf1e94a80748ad19f8bc8ab4e15f540700028a6 Mon Sep 17 00:00:00 2001 From: rdev32 Date: Wed, 19 Apr 2023 11:36:15 -0500 Subject: [PATCH 2/8] feat: add process.argv and promisify solution --- 1-callbacks/other-solution.js | 62 +++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 1-callbacks/other-solution.js diff --git a/1-callbacks/other-solution.js b/1-callbacks/other-solution.js new file mode 100644 index 0000000..dd59b19 --- /dev/null +++ b/1-callbacks/other-solution.js @@ -0,0 +1,62 @@ +/* +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'); + +function solution() { + const names = process.argv.filter((item, index) => index > 1); + const validateAsync = util.promisify(validateName); + + console.log('Success'); + Promise.all(names.map(name => validateAsync(name, callback))); + + setTimeout(() => { + console.log('Failure\n'); + }, 350); + + 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); + } + } +} + +solution() \ No newline at end of file From 6a8abfd9eb7b36442d9d3d2f4b8b590970b64f2a Mon Sep 17 00:00:00 2001 From: rdev32 Date: Wed, 19 Apr 2023 16:44:06 -0500 Subject: [PATCH 3/8] feat: add promises implementation solution --- 2-promises/solution.js | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/2-promises/solution.js b/2-promises/solution.js index 5daa659..7231975 100644 --- a/2-promises/solution.js +++ b/2-promises/solution.js @@ -24,16 +24,25 @@ 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(); + process.stdout.write(`ID: ${id} - `); + lastnames(id).then(lname => { + process.stdout.write(`${lname}, `); + firstnames(lname).then(fname => { + process.stdout.write(`${fname}\n`); + }).catch(error => console.log(error.message)) + }).catch(error => console.log(error.message)); + + function randomId() { + const desire = [1, -1]; + const choice = Math.floor(Math.random() * desire.length); + return (Math.floor(Math.random() * 2)) ? Math.floor(Math.random() * 101) * desire[choice] : Math.floor(Math.random() * 101) * desire[choice] + desire.toString(); + } } solution() From 5fed444692d8d96d4c9631d7b117161b8ef99870 Mon Sep 17 00:00:00 2001 From: rdev32 Date: Fri, 21 Apr 2023 10:16:59 -0500 Subject: [PATCH 4/8] feat: add async await implementation solution --- 3-async-await/solution.js | 104 +++++++++++++++++++++++++++++++++++++- 1 file changed, 102 insertions(+), 2 deletions(-) diff --git a/3-async-await/solution.js b/3-async-await/solution.js index 38e29d9..f90fbe6 100644 --- a/3-async-await/solution.js +++ b/3-async-await/solution.js @@ -19,17 +19,117 @@ 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 + 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), + ]); + + if (!allPromises) throw Error({ cause: allPromises }); + + // Log the results, or errors, here + 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 > 0) throw new Error(promisesRejected); + + // Log the results, or errors, here + console.log({ id, product: promisesFulfilled[1], price: promisesFulfilled[0] }); + + } catch (error) { + console.log('Entered Promise.allSettled catch block'); + console.error(error.message); + } + + + + + // You use Promise.any() here + console.log('\n\tUsing Promise.any\n'); + try { + const anyPromise = await Promise.any([ + prices(id), + products(id), + ]); + + if (!anyPromise) throw new Error({ cause: 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 }); + else + console.log({ id, anyPromise }); + + } catch (error) { + console.log('Entered Promise.race 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), + ]); + + + if (!promiseRace) throw new Error({ cause: promiseRace }); + + // 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 }); + else + console.log({ id, 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() From b168fbd5970f44cfd61461565a1032b296dba1d7 Mon Sep 17 00:00:00 2001 From: rdev32 Date: Sat, 22 Apr 2023 13:13:34 -0500 Subject: [PATCH 5/8] refactor: better use of promisify and more comments --- 1-callbacks/other-solution.js | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/1-callbacks/other-solution.js b/1-callbacks/other-solution.js index dd59b19..b2d68b2 100644 --- a/1-callbacks/other-solution.js +++ b/1-callbacks/other-solution.js @@ -37,26 +37,27 @@ 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'); - Promise.all(names.map(name => validateAsync(name, callback))); - - setTimeout(() => { - console.log('Failure\n'); - }, 350); - - 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); - } + 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); } solution() \ No newline at end of file From 3851526e8c33ff72ea7dc33d7d2af5021f5060ef Mon Sep 17 00:00:00 2001 From: rdev32 Date: Sat, 22 Apr 2023 13:14:15 -0500 Subject: [PATCH 6/8] refactor: add comments --- 1-callbacks/solution.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/1-callbacks/solution.js b/1-callbacks/solution.js index d0cffb3..38d0dc2 100644 --- a/1-callbacks/solution.js +++ b/1-callbacks/solution.js @@ -34,8 +34,10 @@ node solution.js name1 name2 name3 const validateName = require('./validate-user'); function solution() { + // 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) { validateName(name, callback); @@ -45,6 +47,7 @@ function solution() { 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`); From 3383ca4599ea3577f0c1121b0deac43f1370c48b Mon Sep 17 00:00:00 2001 From: rdev32 Date: Sat, 22 Apr 2023 13:24:02 -0500 Subject: [PATCH 7/8] refactor: add description comments --- 2-promises/solution.js | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/2-promises/solution.js b/2-promises/solution.js index 7231975..64b735c 100644 --- a/2-promises/solution.js +++ b/2-promises/solution.js @@ -30,18 +30,28 @@ const lastnames = require('./lastnames'); function solution() { const id = randomId(); - process.stdout.write(`ID: ${id} - `); + + 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`); - }).catch(error => console.log(error.message)) + }).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)) ? Math.floor(Math.random() * 101) * desire[choice] : Math.floor(Math.random() * 101) * desire[choice] + desire.toString(); + return (Math.floor(Math.random() * 2)) ? + Math.floor(Math.random() * 101) * desire[choice] : + Math.floor(Math.random() * 101) * desire[choice] + desire.toString(); // whatever different to a positive integer } } From 2278ad00369a775c574400b54233e4f14bf0e0a7 Mon Sep 17 00:00:00 2001 From: rdev32 Date: Sat, 22 Apr 2023 13:36:53 -0500 Subject: [PATCH 8/8] refactor: add note and description comments --- 3-async-await/solution.js | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/3-async-await/solution.js b/3-async-await/solution.js index f90fbe6..cb4e0c0 100644 --- a/3-async-await/solution.js +++ b/3-async-await/solution.js @@ -26,6 +26,7 @@ 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`); @@ -39,9 +40,6 @@ async function solution() { products(id), ]); - if (!allPromises) throw Error({ cause: allPromises }); - - // Log the results, or errors, here console.log({ id, product: allPromises[1], price: allPromises[0] }); } catch (error) { @@ -62,14 +60,20 @@ async function solution() { 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 > 0) throw new Error(promisesRejected); + 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 + // 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'); - console.error(error.message); + const msg = [error.message].join(' ').split(','); + msg.forEach(err => console.error(err)); } @@ -83,18 +87,16 @@ async function solution() { products(id), ]); - if (!anyPromise) throw new Error({ cause: anyPromise }); + 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 }); - else - console.log({ id, anyPromise }); } catch (error) { - console.log('Entered Promise.race catch block'); + console.log('Entered Promise.any catch block'); console.error(error.message); } @@ -108,17 +110,12 @@ async function solution() { prices(id), products(id), ]); - - - if (!promiseRace) throw new Error({ cause: promiseRace }); // 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 }); - else - console.log({ id, promiseRace }) } catch (error) { console.log('Entered Promise.race catch block');