Skip to content

Instantly share code, notes, and snippets.

@bitbay
Created March 5, 2020 08:29
Show Gist options
  • Save bitbay/48c1cc252e3fcdd8436df5c1bce777b6 to your computer and use it in GitHub Desktop.
Save bitbay/48c1cc252e3fcdd8436df5c1bce777b6 to your computer and use it in GitHub Desktop.
Random helpers
/**
* @param {number} max the upper bound of the result
* @return {number} random number up to (but not including) max value [0, max)
*/
const randomUpTo = max => Math.floor(Math.random() * max);
/**
* @param {number|undefined} prob if defined, probability (percent) of the outcome being true
* @return {boolean} [true|false]
*/
const randomBoolean = (prob = 0.5) => Math.random() > prob;
/**
* @param {Array<*>} array the input array to get a random item from
* @return {*} a random item from the array
*/
const randomArrayItem = array => array[randomUpTo(array.length)];
/**
* @param {number} min lower bound
* @param {number} max upper bound
* @return {number} a random number between lower and upper bounds [min, max)
*/
const randomBetween = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
// public methods, ie. export them goodies!
exports.boolean = () => randomBoolean();
exports.arrayItem = array => randomArrayItem(array);
exports.upTo = max => randomUpTo(max);
exports.between = (min, max) => randomBetween(min, max);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment