Skip to content
This repository has been archived by the owner on Sep 2, 2022. It is now read-only.

Commit

Permalink
Implement randomHexColor and isHexColor utils
Browse files Browse the repository at this point in the history
  • Loading branch information
Ray Foo committed Aug 27, 2022
1 parent 77fcc0f commit 193bafc
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/rare-plums-complain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@busyxiang/utilities-js': patch
---

Implement randomHexColor and isHexColor util
27 changes: 27 additions & 0 deletions src/color.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { randomHexColor, isHexColor } from './color';

describe('isHexColor', () => {
test('it should return true if is valid hex color', () => {
const isValid = isHexColor('#e34155');

expect(isValid).toBe(true);
});

test('it should return false if is invalid input', () => {
const isValid = isHexColor('color');

expect(isValid).toBe(false);
});
});

describe('randomHexColor', () => {
test('it should return a valid hex color', () => {
const regex = /^#[0-9A-F]{6}$/i;

for (let i = 0; i < 10; i++) {
const color = randomHexColor();

expect(regex.test(color)).toBe(true);
}
});
});
10 changes: 10 additions & 0 deletions src/color.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export const randomHexColor = () => {
const code = (Math.random() * 0xfffff * 1000000).toString(16);
return `#${code.slice(0, 6)}`;
};

export const isHexColor = (hexColor: string) => {
const regex = /^#[0-9A-F]{6}$/i;

return regex.test(hexColor);
};

0 comments on commit 193bafc

Please sign in to comment.