Skip to content

Commit

Permalink
feat: support hex shorthand syntax (closes #2)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Oct 13, 2020
1 parent 49cea61 commit 6c99266
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
7 changes: 6 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@ export function parseColor (color = '') {
return hexMatch.splice(1).map(c => parseInt(c, 16))
}

const hexMatchShort = /^#?([a-f\d])([a-f\d])([a-f\d])$/i.exec(color)
if (hexMatchShort) {
return hexMatchShort.splice(1).map(c => parseInt(c + c, 16))
}

if (color.includes(',')) {
return color.split(',').map(p => parseInt(p))
}

throw new Error('Invalid color format! Use #AABBCC or (r,g,b)')
throw new Error('Invalid color format! Use #ABC or #AABBCC or (r,g,b)')
}

export function hexValue (components) {
Expand Down
7 changes: 6 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getColors } from '../src/index'
import { parseColor } from '../src/utils'

const fixture = {
hex: '#ABABAB',
Expand Down Expand Up @@ -26,5 +27,9 @@ test('getColors (rgb)', () => {
})

test('getColors (invalid)', () => {
expect(() => getColors('red')).toThrowError('Invalid color format! Use #RRGGBB or (r,g,b)')
expect(() => getColors('red')).toThrowError(/Invalid color format!/)
})

test('parseColor (shorthand)', () => {
expect(parseColor('#09C')).toEqual(parseColor('#0099cc'))
})

0 comments on commit 6c99266

Please sign in to comment.