Created
September 19, 2020 11:14
-
-
Save utkarsh27a/7697338af285b802527079f21d9b1a14 to your computer and use it in GitHub Desktop.
Shyplite Questions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Question 1: Create an Array from 0...100 without using traditional For-loop | |
function getNumbers(from, to) { | |
let arr = []; | |
while (from <= to) { | |
arr.push(from); | |
from++; | |
} | |
return arr; | |
} | |
let collection = getNumbers(0, 100); | |
console.log({collection}); | |
// Question 2: Create an Array of only even numbers from the above array | |
let evenNumbers = collection.filter((n) => n%2 == 0); | |
console.log({evenNumbers}); | |
// Create a function that returns a Promise which returns the | |
// square of only even numbers and | |
// throws an error if an odd number is passed | |
function checkEvenAndMakeSquare(n) { | |
return new Promise((resolve, reject) => { | |
if (n%2 == 0) { | |
return resolve(n*n); | |
} | |
return reject(new Error("Odd number is passed.")); | |
}) | |
} | |
// Question 3: create an array of even squares using the previous array | |
// direct invocation is important to see if the | |
// candidate understands Arrow functions correctly. | |
evenSquares = []; | |
evenNumbers.forEach(async n => { | |
try { | |
let ns = await checkEvenAndMakeSquare(n); | |
evenSquares.push(ns); | |
} catch (error) { | |
console.log(error); | |
} | |
if (n == 10) { | |
console.log({evenSquares}); | |
} | |
}); | |
// Question 4: Sum of all the squares from the above array of Even Squares | |
setImmediate(() => { | |
let sumOfEvenSquares = 0; | |
evenSquares.forEach(n => { | |
sumOfEvenSquares = sumOfEvenSquares + n; | |
}) | |
console.log({ sumOfEvenSquares }); | |
}); | |
// Question 5: Call the above square Promise function with all numbers from 0-100 | |
// and ensure that the errors are not thrown | |
// then print the following: | |
// 1. Number of errors | |
// 2. The resultant array | |
// 3. Number of objects in the resultant array | |
let resultArr = [], errorCount = 0; | |
collection.forEach(async n => { | |
try { | |
let ns = await checkEvenAndMakeSquare(n); | |
resultArr.push(ns); | |
} catch (error) { | |
errorCount++; | |
} | |
if (n == collection[collection.length - 1]) { | |
console.log({ resultArr, errorCount, resultArrCount: resultArr.length }); | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment