diff --git a/README.md b/README.md index 923e59745..0e1a736b2 100644 --- a/README.md +++ b/README.md @@ -7672,8 +7672,8 @@ Use `Math.random` to generate a random 24-bit(6x4bits) hexadecimal number. Use b ```js const randomHexColorCode = () => { - let n = ((Math.random() * 0xfffff) | 0).toString(16); - return '#' + (n.length !== 6 ? ((Math.random() * 0xf) | 0).toString(16) + n : n); + let n = (Math.random() * 0xfffff * 1000000).toString(16); + return '#' + n.slice(0, 6); }; ``` diff --git a/docs/index.html b/docs/index.html index 366cc80a2..afd1efa7d 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1835,8 +1835,8 @@ Logs: { prettyBytes(-27145424323.5821, 5); // "-27.145 GB" prettyBytes(123456789, 3, false); // "123MB"

randomHexColorCode

Generates a random hexadecimal color code.

Use Math.random to generate a random 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using toString(16).

const randomHexColorCode = () => {
-  let n = ((Math.random() * 0xfffff) | 0).toString(16);
-  return '#' + (n.length !== 6 ? ((Math.random() * 0xf) | 0).toString(16) + n : n);
+  let n = (Math.random() * 0xfffff * 1000000).toString(16);
+  return '#' + n.slice(0, 6);
 };
 
randomHexColorCode(); // "#e34155"
 

RGBToHex

Converts the values of RGB components to a color code.

Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (<<) and toString(16), then String.padStart(6,'0') to get a 6-digit hexadecimal value.

const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
diff --git a/snippets/randomHexColorCode.md b/snippets/randomHexColorCode.md
index 3a06f06ea..af8b723f2 100644
--- a/snippets/randomHexColorCode.md
+++ b/snippets/randomHexColorCode.md
@@ -6,7 +6,7 @@ Use `Math.random` to generate a random 24-bit(6x4bits) hexadecimal number. Use b
 
 ```js
 const randomHexColorCode = () => {
-  let n = (((Math.random() * 0xfffff)) * 1000000).toString(16);
+  let n = (Math.random() * 0xfffff * 1000000).toString(16);
   return '#' + n.slice(0, 6);
 };
 ```