-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHexToRGB.js
More file actions
40 lines (33 loc) · 743 Bytes
/
Copy pathHexToRGB.js
File metadata and controls
40 lines (33 loc) · 743 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// create a RGB array from a hex value
const expect = require('expect');
function hexToRGB(hex) {
hex = hex.trim();
if (hex[0] === '#') {
hex = hex.replace('#', '');
}
if (!valid(hex)) {
throw new Error('Incorrect Hex');
}
const RGB = [];
const r = parseInt(hex.substring(0, 2), 16);
RGB.push(r);
const g = parseInt(hex.substring(2, 4), 16);
RGB.push(g);
const b = parseInt(hex.substring(4, 6), 16);
RGB.push(b);
return RGB;
}
function valid(str) {
const re = /[0-9A-Fa-f]{6}/g;
return re.test(str);
}
const testFunc = () => {
expect(
hexToRGB('ff00ff')
).toEqual([255, 0, 255]);
expect(
hexToRGB('#ff00ff')
).toEqual([255, 0, 255]);
};
testFunc();
console.log('All tests passed');