TLDR: Use for...of
instead of forEach()
in asynchronous code.
For legacy browsers, use for...i
or [].reduce()
To execute the promises in parallel, use Promise.all([].map(...))
/** | |
* | |
* boolean isEmpty ( value ) | |
* | |
* Example: | |
* | |
* var a = null; | |
* if (isEmpty(a)) { | |
* alert ('empty variable'); | |
* } |
function weightedChoice(weights) { | |
const weightSum = weights.reduce((sum, w) => sum + w) | |
let choice = Math.floor(Math.random() * weightSum) + 1 | |
let idx = weights.length - 1 | |
while ((choice -= weights[idx]) > 0) { | |
idx -= 1 | |
} | |
return idx | |
} |