This question already has answers here:
Executing 100K Promises in Javascript in small 50 Chunks
(3 answers)
Closed 2 years ago.
I have a set of requests but they can not be called all simultaneously so I decided to split the set into the chucks of 10.
I am wondering how can I make 10 requests and wait for them all to complete like the example above:
data = []
for(mindex = 0; mindex < 1000; mindex = mindex + 10){
request_chunk = []
for(index = mindex+1; index < mindex+10; index++){
request_chunk.push(api.call(requests[index]).getPromise();
}
data = data + waitPromiseToComplete(request_chunk);
}
You can use Promise.all and await:
(async function () {
const data = []; // always declare variables!
for(let mindex = 0; mindex < 1000; mindex = mindex + 10){
const request_chunk = []
for(let index = mindex + 1; index < mindex + 10; index++){
request_chunk.push(api.call(requests[index]).getPromise();
}
data = data.concat(await Promise.all(request_chunk));
}
})();
Related
This question already has answers here:
Sum all the digits of a number Javascript
(8 answers)
Closed 1 year ago.
I tried to solve but didn't work :
const SumOf = (N) => {
var res = N.toString().split("");
var total = 0;
for (i = 0; i < N; i++) {
total += res[i]
}
}
You can simply write:
const sumN = (number) => {
const nArray = number.split("").map(n=> +n)
return nArray.reduce((acc, cur)=> acc+=cur, 0)
}
console.log(sumN("123"))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
In response I want all 3 digit numbers whose sum is 11 and also gives module 1 and
also want to know how can I push 000 in array in js.
For example number = 128, sum = 11 and module(remainder) = 1.
Like this I want all that numbers in array.
Can anyone share the logic for the same.
Thanx in advance.
I'm not sure what the second check is supposed to be (the modulus of something has to be 1). If that is supposed to be that the modulus of all digits of the number has to be 1, here is how you could do it:
var results = [];
for (let i = 1; i < 10; i++) {
for (let j = 0; j < 10; j++) {
for (let k = 0; k < 10; k++) {
if (i + j + k === 11 && i % j % k === 1) {
results.push(i.toString() + j.toString() + k.toString());
}
}
}
}
console.log(results);
OR:
var results = [];
for (let i = 100; i < 1000; i++) {
const [one, two, three] = i.toString().split('').map(i => +i);
if (one + two + three === 11 && one % two % three === 1) {
results.push(i.toString());
}
}
console.log(results);
Basically just go through all the possible combination and do the checks on each number.
Is this what you want?
var arr=[1,128,15];
var remainder = 127;
var result = arr.filter(function(i) {
var str=i.toString().split('');
var sum=0;
str.forEach(function(c) { return sum+=Number(c); });
return sum===11 && (i%remainder)===1;
});
and more fancy and ES6:
const arr=[1,128,15];
const remainder = 127;
const result = arr.filter(i=>{
const sum=i.toString().split('').reduce((s,v)=>(+v)+s,0);
return sum===11 && (i%remainder)===1;
});
You could take a brute force approach and check the sum with eleven. A check with the remainder is not necessary, because 11 has always a rest of one, if divided by ten.
const
getSum = v => [...v.toString()].reduce((a, b) => a + +b, 0),
values = [];
for (let i = 1; i < 1000; i++) {
if (getSum(i) === 11) values.push(i);
}
console.log(values);
.as-console-wrapper { max-height: 100% !important; top: 0; }
This question already has answers here:
async loading javascript with document.write
(5 answers)
How do I add a delay in a JavaScript loop?
(32 answers)
Closed 3 years ago.
I have a code to print a pyramid pattern using callback in javascript.
Right now I am able to load entire code after 2 sec.
I need to print pattern rows after 2 sec interval of time instead loading it at a whole using call back and promises . How can I do it ?
var n = 5;
for (var i = 0; i < n; i++) {
getStar(i, n).then(star => console.log(star));
}
function getStar(i, n) {
return new Promise((resolve, reject) => {
var str = '';
for (var j = 1; j < n - i; j++) {
str = str + ' ';
}
for (var k = 1; k <= (2 * i + 1); k++) {
str = str + '*';
}
setTimeout(() => {
resolve(str);
}, 2000)
})
}
I have a very big array which looks similar to this
var counts = ["gfdg 34243","jhfj 543554",....] //55268 elements long
this is my current loop
var replace = "";
var scored = 0;
var qgram = "";
var score1 = 0;
var len = counts.length;
function score(pplaintext1) {
qgram = pplaintext1;
for (var x = 0; x < qgram.length; x++) {
for (var a = 0, len = counts.length; a < len; a++) {
if (qgram.substring(x, x + 4) === counts[a].substring(0, 4)) {
replace = parseInt(counts[a].replace(/[^1-9]/g, ""));
scored += Math.log(replace / len) * Math.LOG10E;
} else {
scored += Math.log(1 / len) * Math.LOG10E;
}
}
}
score1 = scored;
scored = 0;
} //need to call the function 1000 times roughly
I have to loop through this array several times and my code is running slowly. My question is what the fastest way to loop through this array would be so I can save as much time as possible.
Your counts array appears to be a list of unique strings and values associated with them. Use an object instead, keyed on the unique strings, e.g.:
var counts = { gfdg: 34243, jhfj: 543554, ... };
This will massively improve the performance by removing the need for the O(n) inner loop by replacing it with an O(1) object key lookup.
Also, avoid divisions - log(1 / n) = -log(n) - and move loop invariants outside the loops. Your log(1/len) * Math.LOG10E is actually a constant added in every pass, except that in the first if branch you also need to factor in Math.log(replace), which in log math means adding it.
p.s. avoid using the outer scoped state variables for the score, too! I think the below replicates your scoring algorithm correctly:
var len = Object.keys(counts).length;
function score(text) {
var result = 0;
var factor = -Math.log(len) * Math.LOG10E;
for (var x = 0, n = text.length - 4; x < n; ++x) {
var qgram = text.substring(x, x + 4);
var replace = counts[qgram];
if (replace) {
result += Math.log(replace) + factor;
} else {
result += len * factor; // once for each ngram
}
}
return result;
}
I started making a function that will be able do the following: Count how many 6 digit numbers you can make with the digits 0,1,2,3,4 and 5, that can be divided by 6?
How I currently try to start, is I make an array of all the possible numbers, then take out every number that has any of the numbers' arrays elements in it, then remove the ones that are not dividable with 6.
I got stuck at the second part. I tried making 2 loops to loop in the array of numbers, then inside that loop, create an other one for the length of the allnumbers array to remove all matches.
Then I would use the % operator the same way to get every element out that doesn't return 0.
The code needs to be flexible. If the user asks for eg. digit 6 too, then the code should still work. Any way I could finish this?
My Code is:
var allnumbers = [],j;
var biggestnumber = "999999999999999999999999999999999999999999999999999999999999";
function howmanynumbers(digits,numbers,divideWith){
if (digits && numbers && divideWith){
for (var i = 0; i < 1+Number(biggestnumber.substring(0,digits)); i++ ){
allnumbers.push(i);
}
for (j = 0; j < numbers.length; j++ ){
var matchit = new RegExp(numbers[j]);
}
//not expected to work, I just had this in for reference
if ( String(allnumbers[i]).match(matchit) != [""]){
j = 0;
allnumbers.splice(i,1);
var matchit = new RegExp(numbers[j])
}
}
else {
return false;
}
}
This is my take on the entire solution:
var i;
var allowedDigitsPattern = /^[0-5]+$/i;
var numbers = [];
for (i = 100000; i < 555555; i++) {
if (allowedDigitsPattern.test(i.toString())
&& i % 6 === 0) {
numbers.push(i);
}
}
And you can look at your results like this:
document.write('There are ' + numbers.length + ' numbers<br>');
// write out the first ten!
for (i = 0; i < 10; i++) {
document.write(numbers[i] + '<br>');
}
Update based on comments...
The configurable version of this would be:
var i;
var lowestDigit = 0;
var highestDigit = 5;
var numberOfDigits = 6;
var allowedDigitsPattern = new RegExp('^[' + lowestDigit + '-' + highestDigit + ']+$', 'gi');
var smallestNumber = '1';
for (i = 1; i < numberOfDigits; i++) {
smallestNumber += '0';
}
var biggestNumber = '';
for (i = 0; i < numberOfDigits; i++) {
biggestNumber += highestDigit.toString();
}
var numbers = [];
for (i = smallestNumber; i < biggestNumber; i++) {
if (allowedDigitsPattern.test(i.toString())
&& i % 6 === 0) {
numbers.push(i);
}
}
document.write('There are ' + numbers.length + ' numbers<br>');
You need to change the smallest and largest numbers based on the configuration. I have made both the allowable digits and the length of the number configurable.