Merge pull request #230 from wojtekmaj/bugfix/hexToRgb
hexToRgb: Fix returning wrong value for short hash without # symbol, fix extendHex called 3 times
This commit is contained in:
@ -6,12 +6,11 @@ Use bitwise right-shift operator and mask bits with `&` (and) operator to conver
|
||||
|
||||
```js
|
||||
const hexToRgb = hex => {
|
||||
const extendHex = shortHex =>
|
||||
const extendHex = shortHex =>
|
||||
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('');
|
||||
return hex.slice(1).length==3 ?
|
||||
`rgb(${parseInt(extendHex(hex).slice(1), 16) >> 16}, ${(parseInt(extendHex(hex).slice(1), 16) & 0x00ff00) >> 8}, ${parseInt(extendHex(hex).slice(1), 16) & 0x0000ff})`:
|
||||
`rgb(${parseInt(hex.slice(1), 16) >> 16}, ${(parseInt(hex.slice(1), 16) & 0x00ff00) >> 8}, ${parseInt(hex.slice(1), 16) & 0x0000ff})`;
|
||||
}
|
||||
const extendedHex = hex.slice(hex.startsWith('#') ? 1 : 0).length === 3 ? extendHex(hex) : hex;
|
||||
return `rgb(${parseInt(extendedHex.slice(1), 16) >> 16}, ${(parseInt(extendedHex.slice(1), 16) & 0x00ff00) >> 8}, ${parseInt(extendedHex.slice(1), 16) & 0x0000ff})`;
|
||||
}
|
||||
// hexToRgb('#27ae60') -> 'rgb(39, 174, 96)'
|
||||
// hexToRgb('#acd') -> 'rgb(170, 204, 221)'
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user