Friday, February 29, 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

No comments:

Post a Comment