Cofounded Host Collective (DiscountASP.net). Cofounded Player Axis (Social Gaming). Computer Scientist and Technology Evangelist with 20+ years of experience with JavaScript!
So the complexity actually comes from the requirements you give it.
But asking for a random integer is a common task. So it's handy to create function and keep it in your library. Don't go sprinkling Math.floor(Math.random() * 10) randomly around your codebase :D
P.S. I prefixed this with pseudo because there is no true Random in JavaScript. This is very important when it comes to cryptography. Google PRNG if you want to learn more.
Cofounded Host Collective (DiscountASP.net). Cofounded Player Axis (Social Gaming). Computer Scientist and Technology Evangelist with 20+ years of experience with JavaScript!
Pellentesque nec neque ex. Aliquam at quam vitae lacus convallis pulvinar. Mauris vitae ullamcorper lacus. Cras nisi dui, faucibus non dolor quis, volutpat euismod massa. Donec et pulvinar erat.
Math.random()
produces a randomfloat
(all JavaScript numbers are of typefloat
) from0
to1
.Adding the requirement of 0-10 means you have to multiply by 10 or
* 10
.The last requirement was the number must be an
Integer
, which is themath.floor
.Of course, if you only wanted a random float between
0
and1
, it would be just one call.And in PHP if you wanted a random float between 0 and 1, you would also have to do more work: Random Float between 0 and 1 in PHP
So the complexity actually comes from the requirements you give it.
But asking for a random integer is a common task. So it's handy to create function and keep it in your library. Don't go sprinkling
Math.floor(Math.random() * 10)
randomly around your codebase :DP.S. I prefixed this with
pseudo
because there is no true Random in JavaScript. This is very important when it comes to cryptography. GooglePRNG
if you want to learn more.For a cryptographically strong random value, you might want to look into Crypto.getRandomValues()
Cheers!
I wish PM's understood this more.
There's a bug in your example; if the output is supposed to be
[start, end)
, then the correct implementation is:✌😉
I probably should have run it once. lol.
I gotta stop typing code directly into editors.
Good catch!