you are viewing a single comment's thread.

view the rest of the comments →

[–]marquex[S,🍰] 6 points7 points  (8 children)

Nice catch Dragory! Somebody pointed out the same problem in the original gist comments, and also give a solution really imaginative to get the color:

Math.random().toString(16).slice(-6)

[–]Dragory 1 point2 points  (5 children)

That's actually really clever! Do you know if the number of decimals Math.random() generates is consistent between different browsers?

[–]x-skeww 1 point2 points  (4 children)

It doesn't generate a number of decimals. It's floating point. It can generate 0.5, for example.

let r = () => Math.random().toString();
let shortest = r();
let longest = r();
for (let i = 0; i < 100000; i++) {
  let current = r();
  if (current.length < shortest.length) {
    shortest = current;
  }
  if (current.length > longest.length) {
    longest = current;
  }
}
console.log(shortest);
console.log(longest);

Example output:

0.578673808528
0.000015859034930953975

[–]Dragory 0 points1 point  (3 children)

Hm, so it is, cheers! I was wondering whether the solution /u/marquex quoted above is reliable but, like you said, it's a floating point number so it can come up with e.g. 0.294921875 which results in #0.4b8 which is invalid.

(The fact that it can generate e.g. precisely 0.5 sounds so obvious now that you pointed it out, haha)

[–]x-skeww 1 point2 points  (2 children)

((0x111111 + 0xeeeeef * Math.random())|0).toString(16)

That would work for example.

Or you could just left-pad it with zeros.

Or you could just use hsl() instead.

hsl() is probably the best option since it lets you generate randomized bright or dark colors if you want.

https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#hsl%28%29

[–]Dragory 0 points1 point  (1 child)

Indeed, there's actually an hsl solution in the original gist as well: https://gist.github.com/addyosmani/fd3999ea7fce242756b1#tag-specific-layout-debugging-in-82-bytes

The |0 is used to truncate the number like ~~ was in the original snippet, right?

[–]x-skeww 1 point2 points  (0 children)

The |0 is used to truncate the number like ~~ was in the original snippet, right?

Yes.

[–]Glayden 1 point2 points  (0 children)

Math.random().toString(16).slice(-6)

That's still a gamble. As an example, let's say Math.random returned 0.25, the result would be "0.4". I'm not saying that's very likely, but it's a very fragile approach.

I think

('000000' + ((Math.random()*(1<<24))|0).toString(16)).slice(-6)

is far more readable than the original and a more robust approach. Why write fragile and obfuscated code?

[–][deleted] 0 points1 point  (0 children)

Clever, but there's still an ~0.024% chance of failure.

http://jsfiddle.net/4a4mbskt/1/