-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcolor_converter.js
77 lines (62 loc) · 2.12 KB
/
color_converter.js
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Convert a decimal integet to it's hexadecimal representation
* @param {number} n number in decimal notation
* @return {number} number in hexadecimal notation
*/
const hexToDecimal = n => {
return parseInt(n, 16);
};
/**
* Convert RGB color code to it's hexadecimal representation
* @param {string} hexCode A color hex code, with or without it's hash prefix
* @return {string} A string with the rgb color e.g., rgb(135, 20, 55)
*/
const hexToRgb = hexCode => {
const i = hexCode.length === 6 ? 0 : 1;
const r = hexCode.slice(i, i + 2);
const g = hexCode.slice(i + 2, i + 4);
const b = hexCode.slice(i + 4, i + 6);
return `rgb(${hexToDecimal(r)}, ${hexToDecimal(g)}, ${hexToDecimal(b)})`;
};
/**
* Convert RGB color code to it's hexadecimal representation
* @param {string, number, array} r The red component or a full array
* @param {string, number} g The green component
* @param {string, number} b The blue component
* @return {string} A string with the hexcode e.g., #0C56B1
*/
const rgbToHex = (r, g, b) => {
const hexValues = '0123456789ABCDEF';
const hexResult = [];
let rgbCode;
if (r === undefined) {
return 'Invalid RGB code provided';
}
if (typeof r !== 'object' && (!g === undefined || !b === undefined)) {
return 'Invalid RGB code provided'
} else if (typeof r === 'object') {
rgbCode = r.join(',')
} else {
rgbCode = `${r},${g},${b}`;
}
const colorCodes = rgbCode.matchAll(/\d{1,3}/g);
for (const [color] of colorCodes) {
colorCode = parseInt(color, 10);
if (colorCode < 0 || colorCode > 255) {
return 'Invalid RGB code provided';
}
const temp = [];
// Math explanation: https://www.rapidtables.com/convert/number/how-decimal-to-hex.html
for (let quotient = 1; quotient > 0; colorCode = quotient) {
quotient = Math.floor(parseInt(colorCode, 10) / 16);
const remainder = colorCode % 16;
const hexCode = hexValues[remainder % 16];
temp.unshift(hexCode);
}
if (temp.length < 2) {
temp.unshift(0);
}
hexResult.push(temp.join(''));
}
return `#${hexResult.join('')}`;
};