Skip to content

Commit

Permalink
adding tests (#814)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukasoppermann authored Feb 23, 2024
1 parent 0394f6d commit 0f272e0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
20 changes: 20 additions & 0 deletions src/transformers/utilities/isRgbaFloat.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {isRgbaFloat} from './isRgbaFloat'

describe('Utilities: isRgbaFloat', () => {
it('valid RgbaFloat', () => {
expect(isRgbaFloat({a: 1, b: 0.6, g: 0.4, r: 0.2})).toStrictEqual(true)
expect(isRgbaFloat({a: 0, b: 0.2, g: 0.4, r: 0.2})).toStrictEqual(true)
expect(isRgbaFloat({b: 0.6, g: 0.4, r: 0.2})).toStrictEqual(true)
})

it('RgbaFloat as string', () => {
expect(isRgbaFloat('{a: 1, b: 0.6, g: 0.4, r: 0.2}')).toStrictEqual(false)
})
it('Invalid values', () => {
expect(isRgbaFloat({a: 1, b: 0.6, g: 0.4})).toStrictEqual(false)
expect(isRgbaFloat({a: 1, b: 0.6, g: 0.4, r: 1.1})).toStrictEqual(false)
expect(isRgbaFloat('#334455')).toStrictEqual(false)
expect(isRgbaFloat(undefined)).toStrictEqual(false)
expect(isRgbaFloat(null)).toStrictEqual(false)
})
})
12 changes: 9 additions & 3 deletions src/transformers/utilities/isRgbaFloat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,23 @@ export type RgbaFloat = {
a?: number
}

// sum up the values of all values in an array
const sum = (array: unknown[]): number => array.reduce((acc: number, v: unknown) => acc + parseInt(`${v}`), 0)
// check if a value is an rgba float object
export const isRgbaFloat = (value: unknown): value is RgbaFloat => {
if (
value &&
typeof value === `object` &&
'r' in value &&
typeof value.r === `number` &&
'g' in value &&
typeof value.g === `number` &&
'b' in value &&
sum([value.r, value.g, value.b]) < 5
typeof value.b === `number` &&
value.r >= 0 &&
value.r <= 1 &&
value.g >= 0 &&
value.g <= 1 &&
value.b >= 0 &&
value.b <= 1
) {
return true
}
Expand Down

0 comments on commit 0f272e0

Please sign in to comment.