Skip to content

Instantly share code, notes, and snippets.

@SynCap
Created September 22, 2018 14:59
Show Gist options
  • Save SynCap/ebda8b0c9c02174143650db8b49fbecd to your computer and use it in GitHub Desktop.
Save SynCap/ebda8b0c9c02174143650db8b49fbecd to your computer and use it in GitHub Desktop.
Javascript universal random function (ES6+ !!!)
function __randomN(...args) {
if (Array.isArray(args[0])) return __randomN(args[0]);
function getRandomIntMax(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}
switch (args.length) {
case 0:
return Math.random();
case 1:
return getRandomIntMax(args[0]);
default:
return getRandomIntInclusive(args[0], args[1]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment