Skip to content

Commit 189ebd4

Browse files
chore: add tests to hex2rgba function
1 parent 47e8029 commit 189ebd4

2 files changed

Lines changed: 67 additions & 2 deletions

File tree

src/utils/hex2rgba.test.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { hex2rgba } from './hex2rgba'
2+
3+
describe('hex2rgba', () => {
4+
// Test wrong hex code
5+
it('should handle wrong hex code - 1', () => {
6+
const hex = '#test'
7+
const expected = 'rgba(0, 0, 0, 0.75)'
8+
const result = hex2rgba(hex)
9+
expect(result).toEqual(expected)
10+
})
11+
12+
it('should handle wrong hex code - 2', () => {
13+
const hex = 'test'
14+
const expected = 'rgba(0, 0, 0, 0.75)'
15+
const result = hex2rgba(hex)
16+
expect(result).toEqual(expected)
17+
})
18+
19+
it('should handle wrong hex code - 3', () => {
20+
const hex = '#<32'
21+
const expected = 'rgba(0, 0, 0, 0.75)'
22+
const result = hex2rgba(hex)
23+
expect(result).toEqual(expected)
24+
})
25+
26+
// Check if function correctly converts hex code to rgba
27+
it('should convert a 3-digit hex code to rgba format', () => {
28+
const hex = '#abc'
29+
const expected = 'rgba(170,187,204,0.75)'
30+
const result = hex2rgba(hex)
31+
expect(result).toEqual(expected)
32+
})
33+
34+
it('should convert a 6-digit hex code to rgba format', () => {
35+
const hex = '#abcdef'
36+
const expected = 'rgba(171,205,239,0.75)'
37+
const result = hex2rgba(hex)
38+
expect(result).toEqual(expected)
39+
})
40+
41+
it('should convert a 3-digit hex code with custom alpha value to rgba format', () => {
42+
const hex = '#abc'
43+
const alpha = 0.5
44+
const expected = 'rgba(170,187,204,0.5)'
45+
const result = hex2rgba(hex, alpha)
46+
expect(result).toEqual(expected)
47+
})
48+
49+
it('should convert a 6-digit hex code with custom alpha value to rgba format', () => {
50+
const hex = '#abcdef'
51+
const alpha = 0.25
52+
const expected = 'rgba(171,205,239,0.25)'
53+
const result = hex2rgba(hex, alpha)
54+
expect(result).toEqual(expected)
55+
})
56+
})

src/utils/hex2rgba.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,20 @@
11
export const hex2rgba = (hex: string, alpha = 0.75) => {
2+
if (!hex || !hex.startsWith('#') || (hex.length !== 4 && hex.length !== 7)) {
3+
return `rgba(0, 0, 0, ${alpha})`
4+
}
25
const newHex =
36
hex.length === 4
47
? hex.split('').reduce((prev, curr) => {
58
return prev + curr + curr
69
})
710
: hex
8-
// @ts-expect-error: object is possibly null
9-
const [r, g, b] = newHex.match(/\w\w/g).map((x) => parseInt(x, 16))
11+
12+
const hexRegex = newHex.match(/\w\w/g)
13+
14+
if (hexRegex?.some((x) => !x) || hexRegex?.length !== 3) {
15+
return `rgba(0, 0, 0, ${alpha})`
16+
}
17+
18+
const [r, g, b] = hexRegex?.map((x) => parseInt(x, 16)) ?? [0, 0, 0]
1019
return `rgba(${r},${g},${b},${alpha})`
1120
}

0 commit comments

Comments
 (0)