Skip to content

Commit

Permalink
fixes & tests (#815)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukasoppermann authored Feb 23, 2024
1 parent 0f272e0 commit 9ec4b18
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
16 changes: 16 additions & 0 deletions src/transformers/utilities/rgbaFloatToHex.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {rgbaFloatToHex} from './rgbaFloatToHex'

describe('Utilities: rgbaFloatToHex', () => {
it('valid RgbaFloat value', () => {
expect(rgbaFloatToHex({a: 1, b: 0.6, g: 0.4, r: 0.2})).toStrictEqual('#336699')
expect(rgbaFloatToHex({a: 0, b: 0.3, g: 0.4, r: 0.2})).toStrictEqual('#33664c')
expect(rgbaFloatToHex({b: 0.6, g: 0.4, r: 0.2})).toStrictEqual('#336699')
expect(rgbaFloatToHex({b: 0.56, g: 0.35, r: 0.123344})).toStrictEqual('#1f598e')
})

it('Invalid values', () => {
expect(() => rgbaFloatToHex({a: 1, b: 0.6, g: 0.4, r: 2})).toThrow(
'Invalid RgbaFloat value. R, G and B values must be between 0 and 1',
)
})
})
12 changes: 11 additions & 1 deletion src/transformers/utilities/rgbaFloatToHex.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
export const rgbaFloatToHex = ({r, g, b, a}: {r: number; g: number; b: number; a?: number}, alpha = true): string => {
const values = [r, g, b, alpha === true && a && a < 1 ? a : undefined].filter(item => item !== undefined) as number[]

return `#${values.map(v => `${(v * 255).toString(16)}`.padStart(2, '0')).join('')}`
if (r > 1 || r < 0 || g > 1 || g < 0 || b > 1 || b < 0) {
throw new Error('Invalid RgbaFloat value. R, G and B values must be between 0 and 1.')
}

return `#${values
.map(v =>
Number(parseInt(`${v * 255}`, 10))
.toString(16)
.padStart(2, '0'),
)
.join('')}`
}

0 comments on commit 9ec4b18

Please sign in to comment.