-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHEXtoANSI.js
59 lines (44 loc) · 1.57 KB
/
HEXtoANSI.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
function HexColorText(text, hexColor) {
// Validate hex color length
if (hexColor.length !== 4 && hexColor.length !== 7) {
throw new Error("Hex color must be either 4 or 7 characters long");
}
// Remove '#' if present
hexColor = hexColor.replace("#", "");
// Convert hex to RGB
const rgb = [
parseInt(hexColor.substring(0, 2), 16),
parseInt(hexColor.substring(2, 4), 16),
parseInt(hexColor.substring(4, 6), 16),
];
// ANSI escape codes for color
const colorCode = `\x1b[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
// ANSI escape code for resetting color
const resetCode = "\x1b[0m";
// Combine color code, text, and reset code
const coloredText = `${colorCode}${text}${resetCode}`;
return coloredText;
}
function HexColorBackground(text, hexColor) {
// Validate hex color length
if (hexColor.length !== 4 && hexColor.length !== 7) {
throw new Error("Hex color must be either 4 or 7 characters long");
}
// Remove '#' if present
hexColor = hexColor.replace("#", "");
// Convert hex to RGB
const rgb = [
parseInt(hexColor.substring(0, 2), 16),
parseInt(hexColor.substring(2, 4), 16),
parseInt(hexColor.substring(4, 6), 16),
];
// ANSI escape codes for color
const colorCode = `\x1b[48;2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
// ANSI escape code for resetting color
const resetCode = "\x1b[0m";
// Combine color code, text, and reset code
const coloredText = `${colorCode}${text}${resetCode}`;
return coloredText;
}
const HEXtoANSIfuncs = { HexColorText, HexColorBackground };
module.exports = HEXtoANSIfuncs;