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

JS Async Challenges #16

Open
wants to merge 1 commit 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
41 changes: 34 additions & 7 deletions 1-callbacks/solution.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,40 @@ node solution.js name1 name2 name3
*/

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 validateUser = require('./validate-user');
let TestUsers=[];
const AllowedUsers = [];
const NotAllowedUsers = [];

// Include process module to support arguments from the console
const process = require('process');
var args = process.argv;
if(args.length === 2){ //If there are no arguments coming , we setup a couple of test names
TestUsers=['Sam', 'Mary', 'Juan', 'Stacy','Jimmy'];
}
else{
args.forEach((val, index) => {
if(index>1)
TestUsers.push(val);
});
}

const cbFn=(error,data) => {
if(error){
NotAllowedUsers.push(error.message)
}
else{
AllowedUsers.push(`id: ${data.id}\nname: ${data.name}`);
}

if(AllowedUsers.length+NotAllowedUsers.length === TestUsers.length){ //Once all names have been processed we print the result
console.log('Success\n\n',AllowedUsers.join('\n\n'));
console.log('\nFailure\n\n',NotAllowedUsers.join('\n'));
}
};
TestUsers.forEach(function(user){
validateUser(user,cbFn)
})
}

solution()
Expand Down
38 changes: 32 additions & 6 deletions 2-promises/solution.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,41 @@ const id = yourRandomMethod() //third run
*/

function solution() {
// YOUR SOLUTION GOES HERE
const getFirstName = require('./firstnames');
const getLastName = require('./lastnames');
let fullName = 'Full Name: ';

// You generate your id value here
const getRandomId = () =>{
let randomizer= Math.floor(Math.random() * 10);
let randomString = '';
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 6; i++) {
randomString += characters.charAt(Math.floor(Math.random() * characters.length));
}
if(randomizer <=3) //returns a number
return Math.floor(Math.random() * 100);
if(randomizer===4) //returns a boolean
return Math.random() < 0.5;
if(randomizer===5) //returns undefined
return undefined;
if(randomizer==6) //returns a random string
return null;
return randomString;
}

// You call the lastnames method with your id
const id = getRandomId();
console.log(`Testing with ID: ${id}`);
getLastName(id)
.then(lastName => {
fullName+= lastName
return getFirstName(lastName)

// You call the firstname method

// You log the fullname, or error, here
})
.then(firstName => {
fullName += ' ' + firstName
console.log(fullName)
})
.catch(err => console.log(err.message))
}

solution()
81 changes: 75 additions & 6 deletions 3-async-await/solution.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,85 @@ Example:
9. as extra challenge: add Promise.race() and Promise.any(), and try to get the idea of what happens
*/

function solution() {
// YOUR SOLUTION GOES HERE
const { CLIENT_RENEG_LIMIT } = require('tls');

// You generate your id value here
async function solution() {
const getProducts = require('./products');
const getPrices = require('./prices');
//Function to generate a random ID
const getId = () =>{
return Date.now().toString().slice(-2);
}
const id = getId();

// You use Promise.all() here
console.log(`Testing for ID: ${id}`);
const handlePromiseAll = (res) =>{
console.log('Processing Promise ALL');
if(typeof res[0] ==='string' ){
console.log({id:id,product: res[0],price:res[1]})
}
else{
console.log({id:id,product: res[1],price:res[0]})
}
}

const handleAllSettled = (res) =>{
console.log('\nProcessing ALL settled');
if(res[0].status && res[1].status === 'fulfilled'){
if(typeof res[0].value ==='string' ){
console.log({id:id,product: res[0].value,price:res[1].value})
}
else{
console.log({id:id,product: res[1].value,price:res[0].value})
}
}
else{
console.log('An error has ocurred when fetching the products or prices');
}
}

try{
//Creation of new promises for Products and Prices
const products = new Promise((resolve) => {
resolve(getProducts(Number(id)));
});
const prices = new Promise((resolve) => {
resolve(getPrices(Number(id)));
});

//Preparing the arry of promises
const productsAndPrices=[products,prices];

//executing all promises at once with Promise.all and Promise.allSettled
const results =await Promise.all(productsAndPrices);
handlePromiseAll(results);

const settled=await Promise.allSettled(productsAndPrices);
handleAllSettled(settled);

//Extra promise race and any
console.log('\nResults for Promise Race')
Promise.race(productsAndPrices).then((value) => {
if(typeof value ==='string' )
console.log(`Products (${value}) settled first!`)
else
console.log(`Price (${value}) settled first!`)
});

Promise.any(productsAndPrices).then((value) => {
if(typeof value ==='string' )
console.log(`Products (${value}) fulfilled first!`)
else
console.log(`Price (${value}) fulfilled first!`)
});
}
catch(error){
console.log('An error has ocurred while fetching the products or prices');
}

//Promise Race

// You use Promise.allSettled() here

// Log the results, or errors, here
}

solution()