[Codewars/JS] RGB To Hex Conversion
The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value.
Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.
The following are examples of expected output values:
rgb(255, 255, 255) // returns FFFFFF
rgb(255, 255, 300) // returns FFFFFF
rgb(0,0,0) // returns 000000
rgb(148, 0, 211) // returns 9400D3
<code>
function rgb(r, g, b) {
r > 255 || r <= 0 //255보다 크거나 0보다 크거나 같으면
? r > 255
? (r16 = "FF")
: (r16 = "00")
: (r16 = r.toString(16).toUpperCase()); //JavaScript의 toString() 함수를 사용하여 RGB를 HEX로 변환
g > 255 || g <= 0
? g > 255
? (g16 = "FF")
: (g16 = "00")
: (g16 = g.toString(16).toUpperCase());
b > 255 || b <= 0
? b > 255
? (b16 = "FF")
: (b16 = "00")
: (b16 = b.toString(16).toUpperCase());
if (r16.length == 1) {
r16 = "0" + r16;
}
if (g16.length == 1) {
g16 = "0" + g16;
}
if (b16.length == 1) {
b16 = "0" + b16;
}
result = r16 + g16 + b16;
return console.log(result);
}
rgb(14, 14, 89);
자꾸 늘어나는 조건을 달고싶지만,, 점점 지저분해지는 코드
클린 코드가 시급하다.. 일단 풀었지만 다른 사람들의 코드를 비교해 보았다.
<other code>
function rgb(r, g, b) {
return console.log(toHex(r) + toHex(g) + toHex(b));
}
function toHex(num) {
if (num <= 0) return "00";
if (num > 255) return "FF";
return ("0" + Number(num).toString(16)).slice(-2).toUpperCase();
}
rgb(14, 14, 89);
함수를 사용하는 방법을 사용했다. 왜 이런생각을 못했지? 😓
훨씬 간결하고 깔금한 클린코드가 되었다.
나는 헥사값의 길이를 구하고 그 값이 1일 경우에 직접 0을 붙였는데 여기서는 이미 0을 붙이고 slice(-2)를 활용하여 2개로 잘라버렸다. 어떻게 이런 생각을 했지? 세상에는 똑똑한 사람이 정말 많은 것 같다..! 🤔
★ slice를 음수를 지정한 경우: 배열의 끝에서부터의 길이를 나타낸다. slice(-2)를 하면 배열의 마지막 2개의 요소를 추출합니다.