Created
September 22, 2018 14:59
-
-
Save SynCap/ebda8b0c9c02174143650db8b49fbecd to your computer and use it in GitHub Desktop.
Javascript universal random function (ES6+ !!!)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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