8000 Support 3-character hex, fixes #1 · coreui/coreui-utils@584bfbe · GitHub
[go: up one dir, main page]

Skip to content

Commit 584bfbe

Browse files
committed
Support 3-character hex, fixes #1
1 parent 8b60f4a commit 584bfbe

File tree

2 files changed

+18
-22
lines changed

2 files changed

+18
-22
lines changed

src/hex-to-rgb.js

Lines changed: 8000 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,20 @@ const hexToRgb = color => {
66

77
const hex = color.match(/^#(?:[0-9a-f]{3}){1,2}$/i)
88

9-
if (!hex) {
10-
throw new Error(`${color} is not a valid hex color`)
11-
}
12-
139
let r
1410
let g
1511
let b
1612

17-
if (color.length === 7) {
18-
r = parseInt(color.slice(1, 3), 16)
19-
g = parseInt(color.slice(3, 5), 16)
20-
b = parseInt(color.slice(5, 7), 16)
13+
if (hex && hex.length === 3) {
14+
r = parseInt(hex.slice(0, 1).repeat(2), 16)
15+
g = parseInt(hex.slice(1, 2).repeat(2), 16)
16+
b = parseInt(hex.slice(2, 3).repeat(2), 16)
17+
} else if (hex && hex.length >= 6) {
18+
r = parseInt(hex.slice(1, 3), 16)
19+
g = parseInt(hex.slice(3, 5), 16)
20+
b = parseInt(hex.slice(5, 7), 16)
2121
} else {
22-
r = parseInt(color.slice(1, 2), 16)
23-
g = parseInt(color.slice(2, 3), 16)
24-
b = parseInt(color.slice(3, 5), 16)
22+
throw new Error(`${color} is not a valid hex color`)
2523
}
2624

2725
return `rgba(${r}, ${g}, ${b})`

src/hex-to-rgba.js

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,20 @@ const hexToRgba = (color, opacity = 100) => {
66

77
const hex = color.match(/^#(?:[0-9a-f]{3}){1,2}$/i)
88

9-
if (!hex) {
10-
throw new Error(`${color} is not a valid hex color`)
11-
}
12-
139
let r
1410
let g
1511
let b
1612

17-
if (color.length === 7) {
18-
r = parseInt(color.slice(1, 3), 16)
19-
g = parseInt(color.slice(3, 5), 16)
20-
b = parseInt(color.slice(5, 7), 16)
13+
if (hex && hex.length === 3) {
14+
r = parseInt(hex.slice(0, 1).repeat(2), 16)
15+
g = parseInt(hex.slice(1, 2).repeat(2), 16)
16+
b = parseInt(hex.slice(2, 3).repeat(2), 16)
17+
} else if (hex && hex.length >= 6) {
18+
r = parseInt(hex.slice(1, 3), 16)
19+
g = parseInt(hex.slice(3, 5), 16)
20+
b = parseInt(hex.slice(5, 7), 16)
2121
} else {
22-
r = parseInt(color.slice(1, 2), 16)
23-
g = parseInt(color.slice(2, 3), 16)
24-
b = parseInt(color.slice(3, 5), 16)
22+
throw new Error(`${color} is not a valid hex color`)
2523
}
2624

2725
return `rgba(${r}, ${g}, ${b}, ${opacity / 100})`

0 commit comments

Comments
 (0)
0