Skip to content

Instantly share code, notes, and snippets.

@joeytwiddle
joeytwiddle / async-await-forEach-alternatives.md
Last active June 23, 2024 21:19
Do not use forEach with async-await

Do not use forEach with async-await

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(...))

The problem

@olaferlandsen
olaferlandsen / isEmpty.js
Last active January 24, 2020 16:48
isEmpty is a compilation of functions to check if is a empty value on javascript compatible with ECMA5+
/**
*
* boolean isEmpty ( value )
*
* Example:
*
* var a = null;
* if (isEmpty(a)) {
* alert ('empty variable');
* }
@mogelbrod
mogelbrod / weighted-choice.js
Created February 16, 2016 09:39
Weighted random choice in JavaScript, takes an array of non-negative weights
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
}