Skip to content

Commit 755ae17

Browse files
committed
fix: hex to rgb color
1 parent f71db88 commit 755ae17

File tree

2 files changed

+16
-12
lines changed

2 files changed

+16
-12
lines changed

public/consolidated/javascript.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@
8989
"conversion"
9090
],
9191
"contributors": [],
92-
"code": "function hexToRgb(r, g, b) {\n return (\n \"#\" +\n [r, g, b]\n .map((x) => {\n const hex = x.toString(16);\n return hex.length === 1 ? \"0\" + hex : hex;\n })\n .join(\"\")\n );\n},\n\n// Usage:\nconsole.log(hexToRgb(\"#ff5733\")); // { r: 255, g: 87, b: 51 }\nconsole.log(hexToRgb(\"#ffff\")); // { r: 0, g: 255, b: 255 }\n"
92+
"code": "function hexToRgb(hex) {\n let sanitizedHex = hex.startsWith(\"#\") ? hex.slice(1) : hex;\n\n if (sanitizedHex.length === 3) {\n sanitizedHex = [...sanitizedHex].map((char) => char + char).join(\"\");\n }\n\n const bigint = parseInt(sanitizedHex, 16);\n\n return {\n r: (bigint >> 16) & 0xff, \n g: (bigint >> 8) & 0xff, \n b: bigint & 0xff, \n };\n}\n\n// Usage:\nconsole.log(hexToRgb(\"#ff5733\")); // { r: 255, g: 87, b: 51 }\nconsole.log(hexToRgb(\"#ffff\")); // { r: 0, g: 255, b: 255 }\n"
9393
},
9494
{
9595
"title": "HSL to RGB Color",

snippets/javascript/color-manipulation/hex-to-rgb-color.md

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,21 @@ tags: color,conversion
66
---
77

88
```js
9-
function hexToRgb(r, g, b) {
10-
return (
11-
"#" +
12-
[r, g, b]
13-
.map((x) => {
14-
const hex = x.toString(16);
15-
return hex.length === 1 ? "0" + hex : hex;
16-
})
17-
.join("")
18-
);
19-
},
9+
function hexToRgb(hex) {
10+
let sanitizedHex = hex.startsWith("#") ? hex.slice(1) : hex;
11+
12+
if (sanitizedHex.length === 3) {
13+
sanitizedHex = [...sanitizedHex].map((char) => char + char).join("");
14+
}
15+
16+
const bigint = parseInt(sanitizedHex, 16);
17+
18+
return {
19+
r: (bigint >> 16) & 0xff,
20+
g: (bigint >> 8) & 0xff,
21+
b: bigint & 0xff,
22+
};
23+
}
2024

2125
// Usage:
2226
console.log(hexToRgb("#ff5733")); // { r: 255, g: 87, b: 51 }

0 commit comments

Comments
 (0)