views:

598

answers:

3

Without using any framework..

I wrote 2 functions:

function get_random_color() 
{
    var color = "";
    for(var i = 0; i < 3; i++) {
     var sub = Math.floor(Math.random() * 256).toString(16);
     color += (sub.length == 1 ? "0" + sub : sub);
    }
    return "#" + color;
}

function get_rand_color()
{
    var color = Math.floor(Math.random() * Math.pow(256, 3)).toString(16);
    while(color.length < 6) {
     color = "0" + color;
    }
    return "#" + color;
}

Which would be considered the better one? Are there better ways to do it?

+2  A: 

More succinct:

function get_random_color2() 
{
    var r = function () { return Math.floor(Math.random()*256) };
    return "rgb(" + r() + "," + r() + "," + r() + ")";
}
Aaron F.
You should define the function outside the `get_random_color2` function... Redefining a function for every call feels a bit unnecessary. The solution that was linked earlier was better, because it only called `Math.random` once, then used bit shifting to get the red/green/blue components.
Blixt
+3  A: 

I like your second option, although it can be made a little bit simpler:

// Math.pow is slow, use constant instead.
var color = Math.floor(Math.random() * 16777216).toString(16);
// Avoid loops.
return '#000000'.slice(0, -color.length) + color;
Blixt
I don't think `substr` is deprecated, but it's less standard than `substring` and `slice`. It's worth noting that `substr` behaves differently from `substring` too. Anyways, I changed to `slice` because it makes the code simpler as an extra bonus. =)
Blixt
+5  A: 

A shorter way:

'#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6)
Soubok
Very short solution indeed =) I would give you +1 but I can see this failing in the (admittedly very rare) cases that `Math.random` returns values like `0.0` or `0.5`.
Blixt
true, now it should be ok (and quite close your solution but shorter :)
Soubok
Yup, but now you've got the problem with having to pad the string with 0 (if result is `<= 0xFFFFF`) That's what I'm doing in the second statement.
Blixt
well, now it should be ok.
Soubok
+1: Using the same style (i.e. space between operators etc.), your code is somewhere around 35 characters shorter =) Here's the formatted version of your code I used for comparison: `return '#' + (0x1000000 + Math.random() * 0xFFFFFF).toString(16).substr(1,6);`
Blixt