Get a Random Number with crypto.getRandomValues() in JavaScript
The Road to Random
I'm adding some randomizing functions to bitty. I wanted to use `crypto.getRandomValues()` instead of `Math.random()`. While it's unlikely to matter, I figure using the better tool makes sense.
Here's the core functions:
JavaScript
JavaScript
Snake Eyes
You pass the functions your minimum and maximum values. They spit out a random value. The numbers are inclusive. To simulate rolling a six sided die, you'd do this:
Negative Space
I don't generally need random negative numbers. That's no reason to avoid them. The functions handles them just fine:
Min/Max
The Math. part of the `result` lines is a nice-to-have. It allows you to flip the inputs without breaking the function. I find that useful for negative numbers. Both of these operate on within the same range:
How's That Now?
The crypto. function requires a different approach than Math.. It works by filling an array with random numbers instead of providing a single random output like the Math function.
The approach here makes an array with only one item and populates it with the random number. Then, it uses the remainder operator (%) to get a value in the min/max distance. Finally, the min value is added back in to shift it into the right place.
The float version works by using bytes. It divides the incoming number by 0xFFFFFFFF + 1. That places the result between 0 and 1. We multiply that by the distance between the min and max numbers using the same approach generally used with Math.random().
More Code is Better (in this case)
The crypto functions are notably longer than their Math. counterparts. Take this standard integer approach, for example:
That doesn't matter. The entire point of baking things into functions is to encapsulate the complexity.
-a
Endnotes
Here's the code I used to make sure swaping the min and max worked properly:
test code
JavaScript
JavaScript
;References
Some languages use % as a modulo operator. It's similar, but not quite the same as the remainder. Check the link for details.