-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathquestion3-solution.js
More file actions
72 lines (63 loc) · 1.94 KB
/
Copy pathquestion3-solution.js
File metadata and controls
72 lines (63 loc) · 1.94 KB
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
/*
Question 3:
Write a function that converts HEX to RGB.
Then Make that function autodect the formats so that if you enter HEX color format it returns RGB and if you enter RGB color format it returns HEX.
Bonus: Release this tool as a npm package.*/
const HEX = 'HEX';
const RGB = 'RGB';
function determineColorType(color) {
return /^#[0-9A-F]{6}[0-9a-f]{0,2}$/i.test(color) ? HEX : RGB;
}
function stringToHex(component) {
var hex = component.toString(16);
return hex.length == 1 ? '0' + hex : hex;
}
function convertHexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? [
'rgb(',
parseInt(result[1], 16),
',',
parseInt(result[2], 16),
',',
parseInt(result[3], 16),
')',
].join('')
: null;
}
function stringToRGB(stringColor) {
var matches = /rgb\((\d+),(\d+),(\d+)\)/.exec(stringColor);
return matches
? {
r: parseInt(matches[1]),
g: parseInt(matches[2]),
b: parseInt(matches[3]),
}
: null;
}
function convertRgbToHex(input) {
const rgb = stringToRGB(input);
return '#' + stringToHex(rgb?.r) + stringToHex(rgb?.g) + stringToHex(rgb?.b);
}
function convertColor(input) {
const colorType = determineColorType(input);
switch (colorType) {
case HEX:
return convertHexToRgb(input);
case RGB:
return convertRgbToHex(input);
default:
'error. The requested color type is not supported by this converter.';
break;
}
}
console.log('Test data:', '#D46A6A', '#801515', '#D66A6A');
console.log(convertColor('#D46A6A'));
console.log(convertColor('#801515'));
console.log(convertColor('#D66A6A'));
console.log('---------------------------------');
console.log(convertColor(convertColor('#D46A6A')));
console.log(convertColor(convertColor('#801515')));
console.log(convertColor(convertColor('#D66A6A')));
// NPM package link: https://github.com/IlonaZaika/my-color-converter