Skip to content

Instantly share code, notes, and snippets.

@Magistern
Last active January 17, 2019 14:16
Show Gist options
  • Save Magistern/9eea00c45a43adbd4811fb5414e475a8 to your computer and use it in GitHub Desktop.
Save Magistern/9eea00c45a43adbd4811fb5414e475a8 to your computer and use it in GitHub Desktop.
The missing random number generator for JavaScript with a random number tester function that displays the spread of random numbers on a given iteration count.
function random(min, max) {
/* defaults to: 1-10 */
min = isNaN(+min) ? 1 : +min
max = isNaN(+max) ? 10 : +max
return Math.floor(Math.random() * (max-min+1)+min)
}
/*
examples:
random(1,80) -> 1-80
random() -> 1-10 (using the defaults)
random("") -> 0-10
random(false, true) -> 0-1
random(0.1, 9.5) -> 0-10 but only 10% chance of a 0, and only 50% chance of 10
*/
//To test the spread of your random numbers:
/*
function testRandom(min, max, amount){
const nums = []
for(let i=0; i<amount;i++){
nums.push(random(min, max))
}
const randomCount = Array.from(new Set(nums)).reduce((acc, v)=>Object.assign(acc, acc[v.toString()]=0), {})
nums.forEach(v=>randomCount[v]++)
console.table([randomCount])
}
testRandom(0.2, 5.7, 1000)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment