From 0ef9cf9bb48d1b3569b8bb06ff37493cdd8c2e1a Mon Sep 17 00:00:00 2001 From: Wojciech Maj Date: Mon, 18 Dec 2017 00:38:58 +0100 Subject: [PATCH] Fix hexToRgb returning wrong value for short hash without # symbol, fix extendHex called 3 times --- snippets/hexToRGB.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/snippets/hexToRGB.md b/snippets/hexToRGB.md index e3118ecf3ba..273aafd21c0 100644 --- a/snippets/hexToRGB.md +++ b/snippets/hexToRGB.md @@ -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)' ```