r/javascript • • Mar 02 '19

Useful javascript one-liners.

https://medium.com/@smellycode/js-one-liners-8bc0a6af2345?source=friends_link&sk=a9295a05aef9e514e137fca7eeb89cd1
344 Upvotes

96 comments sorted by

View all comments

6

u/[deleted] Mar 02 '19 edited Mar 02 '19

The last one fails when the random number is smaller than 0x100000. You need to add .padStart(6, '0') at the end to make sure it's 6 characters.

I've also used Math.random().toString(16).slice(-6) to generate random hex colors. There is a very low chance of getting not enough characters and the distribution is pretty uniform, but still not completely safe.

2

u/BluudLust Mar 03 '19

Wouldn't this cause an issue with distribution of colors doing it this way instead of using 3 randoms?

1

u/[deleted] Mar 03 '19

The second method might have very minor issues, but the first is always uniformly distributed. Each of the 24 bits should have equal chance of being 0 or 1, because if you had to pad the 0's, it means the 24 bit integer actually did have at least four 0's at the start, which happens 1/16 of the time.

1

u/BluudLust Mar 03 '19

Really it depends on how uniform the pseudorandom number generator is. For all intents and purposes it's the same, but technically speaking 3 random numbers will be a far more uniform distribution than using one.