|
7 | 7 |
|
8 | 8 | /* eslint-disable no-magic-numbers */ |
9 | 9 | const hexToRgba = (color, opacity = 100) => { |
10 | | - const hex = color.replace('#', '') |
11 | | - const r = parseInt(hex.substring(0, 2), 16) |
12 | | - const g = parseInt(hex.substring(2, 4), 16) |
13 | | - const b = parseInt(hex.substring(4, 6), 16) |
| 10 | + if (typeof color === 'undefined') { |
| 11 | + throw new Error('Hex color is not defined') |
| 12 | + } |
| 13 | + const hex = color.match(/^#(?:[0-9a-f]{3}){1,2}$/i) |
| 14 | + if (!hex) { |
| 15 | + throw new Error(`${color} is not a valid hex color`) |
| 16 | + } |
| 17 | + let r |
| 18 | + let g |
| 19 | + let b |
| 20 | + if (color.length === 7) { |
| 21 | + r = parseInt(color.substring(1, 3), 16) |
| 22 | + g = parseInt(color.substring(3, 5), 16) |
| 23 | + b = parseInt(color.substring(5, 7), 16) |
| 24 | + } else { |
| 25 | + r = parseInt(color.substring(1, 2), 16) |
| 26 | + g = parseInt(color.substring(2, 3), 16) |
| 27 | + b = parseInt(color.substring(3, 5), 16) |
| 28 | + } |
14 | 29 |
|
15 | | - const result = `rgba(${r}, ${g}, ${b}, ${opacity / 100}` |
16 | | - return result |
| 30 | + return `rgba(${r}, ${g}, ${b}, ${opacity / 100}` |
17 | 31 | } |
18 | 32 |
|
19 | 33 | export default hexToRgba |
0 commit comments