This repository was archived by the owner on Feb 20, 2019. It is now read-only.
File tree Expand file tree Collapse file tree 3 files changed +50
-0
lines changed Expand file tree Collapse file tree 3 files changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ export default hex2rgb
2+
3+ /**
4+ * Original Source: http://stackoverflow.com/a/12342275
5+ *
6+ * This method will convert colors in Hex to RGB format.
7+ *
8+ * @param {String } hex - The Hex value to be converted
9+ * @param {Number } opacity - The opacity value of the color
10+ * @return {String } - The RGB value of the color
11+ */
12+ function hex2rgb ( hex , opacity ) {
13+ let h = hex . replace ( '#' , '' )
14+ h = h . match ( new RegExp ( `(.{${ h . length / 3 } })` , 'g' ) )
15+
16+ for ( let i = 0 ; i < h . length ; i ++ ) {
17+ h [ i ] = parseInt ( h [ i ] . length === 1 ? h [ i ] + h [ i ] : h [ i ] , 16 )
18+ }
19+ if ( typeof opacity !== 'undefined' ) {
20+ h . push ( opacity )
21+ }
22+
23+ return `rgba(${ h . join ( ',' ) } )`
24+ }
Original file line number Diff line number Diff line change @@ -9,6 +9,7 @@ import objectValuesToString from './object-values-to-string'
99import getObjectSize from './get-object-size'
1010import isArray from './is-array'
1111import validateEmail from './validateEmail'
12+ import hex2rgb from './hex2rgb'
1213
1314export {
1415 flatten ,
@@ -22,4 +23,5 @@ export {
2223 getObjectSize ,
2324 isArray ,
2425 validateEmail ,
26+ hex2rgb ,
2527}
Original file line number Diff line number Diff line change 1+ import test from 'ava'
2+ import { hex2rgb } from '../src'
3+
4+ test ( 'test hex without opacity value' , t => {
5+ const hex = '#ff0000'
6+ const expected = 'rgba(255,0,0)'
7+ const actual = hex2rgb ( hex )
8+ t . deepEqual ( actual , expected )
9+ } )
10+
11+ test ( 'test hex with opacity value' , t => {
12+ const hex = '#ff0000'
13+ const opacity = 1
14+ const expected = 'rgba(255,0,0,1)'
15+ const actual = hex2rgb ( hex , opacity )
16+ t . deepEqual ( actual , expected )
17+ } )
18+
19+ test ( 'test short hex without opacity value' , t => {
20+ const hex = '#f00'
21+ const expected = 'rgba(255,0,0)'
22+ const actual = hex2rgb ( hex )
23+ t . deepEqual ( actual , expected )
24+ } )
You can’t perform that action at this time.
0 commit comments