My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Saturday, March 01, 2008

[COW] The fastest JavaScript rand ... isn't it ?

Hi guys, the WebReflection COW is a function that's so simple as usual: the php like rand function, to create random number, or random boolean evaluation:

function rand(min, max){
return max ? min + rand(max - min) : Math.random() * ++min << .5;
};

// pseudo packed version, 62 bytes
function rand(m,M){return M?m+rand(M-m):Math.random()*++m<<.5}


What's new? Nothing, but could be useful :lol: ... and it has really good performances

// boolean evaluation
var testMe = rand(1) ? true : false;

Above example is for boolean assignment for random things
The function works as PHP one, creation of something casual apart.
I mean, if you use rand(), why don't you use Math.random() ?
So, basically, this function is to have a random number from 0 to N, where N is the min argument, or from min to max, where MAX is the second one.

rand(2); // 0, 1 or 2
rand(2, 5); // 2, 3, 4 or 5

Have a nice WE

2 comments:

Anonymous said...

Nice, but it has problems with rand(-10, 0). Which needs a few extra characters. ;)

Andrea Giammarchi said...

rand(10)*-1 is the same
rand(20)-10 is equal to rand(-10,10)

So, I wonder if we rally need more code, or simply more Math in our mind :P