Have you ever had to pick a random value from an array or a range of numbers and wished there was a simple one-liner way of doing it? Me too! The following function will get that done for you:
This function will accept zero, one or two arguments:
minOrArray{number | Array} - If a number is given and this is the only argument specified this will be used as thelimitvalue while0will be used as the inclusive boundary for the range of numbers that can be returned. If a number is given andlimitis notundefinedornullthis will be the the inclusive boundary for the range of numbers that can be returned. If an array is given a random value from this array will be returned.limit{number | undefined | null} - If a number is given it will represent the exclusive boundary of the range of numbers from which a random number can be chosen.
This returns a random number in the cases that no arguments are given, one number argument is given or two number arguments are given. This returns a random value from an array in the case that minOrArray is given as an array.
The following will produce a random number from 0 (inclusive) to 1 (exclusive):
// HIDE \\
console.evalGistFile('random.js');
// \\
random() // Don't pass any arguments
// \\
random(1) // Only pass one argument
// \\
random(0, 1) // Pass both arguments
The following will produce a random number from 0 (inclusive) to 50 (exclusive):
// HIDE \\
console.evalGistFile('random.js');
// \\
random(50) // Only pass one argument
// \\
random(0, 50) // Pass both arguments
The following will produce a random number from 5 (inclusive) to 10 (exclusive):
// HIDE \\
console.evalGistFile('random.js');
// \\
random(5, 10) // Pass both arguments
The following will produce a random value from the given array:
// HIDE \\
console.evalGistFile('random.js');
// \\
words = "the quick brown fox jumps over the lazy dog".split(" ");
// \\
random(words) // Get a random word
Check this gistly page out here:
https://www.yourjs.com/gistly/b74b95269ece2ca7bc7c/JavaScript+Snippet+-+random().md