I need my function to convert RGB decimal values into Hexadecimal values without using toString(16). This is what I have. Why isn't it working? Is it because I have more than one switch statement so it completes the iteration without completing the second one?
function rgb(r, g, b){
let result = '';
// Convert into array for iteration
let arr = [r,g,b];
// Iterate through each color
for(let i=0; i<arr.length; i++) {
if (arr[i] > 255) result += 'FF';
if (arr[i] < 0) result += '00';
// Convert first iteration into hex format
switch (Math.floor(arr[i]/16)) {
case 10: result += 'A';break;
case 11: result += 'B';break;
case 12: result += 'C';break;
case 13: result += 'D';break;
case 14: result += 'E';break;
case 15: result += 'F';break;
default: result += (Math.floor(arr[i]/16) + '');
}
// Convert second iteration into hex format
switch (((arr[i]/16)-16)*16) {
case 10: result += 'A';break;
case 11: result += 'B';break;
case 12: result += 'C';break;
case 13: result += 'D';break;
case 14: result += 'E';break;
case 15: result += 'F';break;
default: result += ((((arr[i]/16)-16)*16) + '');
}
}
return result;
}
// function should return the following results.
rgb(255, 255, 255) // returns FFFFFF
rgb(255, 255, 300) // returns FFFFFF
rgb(0,0,0) // returns 000000
rgb(148, 0, 211) // returns 9400D3
A problem is that, when turning a number (eg, 255) into two characters, calculating the second character by using
((arr[i]/16)-16)*16
is not the right calculation. You want a range of 0 to 15 - taking out the multiples of 16 until you're left with 0 to 15. Just use % 16.
Another problem is that you're switching even if past the range of 0 to 255 - break instead so that the rest of the loop body does not execute in such cases.
function rgb(r, g, b){
let result = '';
// Convert into array for iteration
let arr = [r,g,b];
// Iterate through each color
for(let i=0; i<arr.length; i++) {
if (arr[i] > 255) {
result += 'FF';
break;
}
if (arr[i] < 0) {
result += '00';
break;
}
// Convert first iteration into hex format
switch (Math.floor(arr[i]/16)) {
case 10: result += 'A';break;
case 11: result += 'B';break;
case 12: result += 'C';break;
case 13: result += 'D';break;
case 14: result += 'E';break;
case 15: result += 'F';break;
default: result += (Math.floor(arr[i]/16) + '');
}
// Convert second iteration into hex format
switch (arr[i] % 16) {
case 10: result += 'A';break;
case 11: result += 'B';break;
case 12: result += 'C';break;
case 13: result += 'D';break;
case 14: result += 'E';break;
case 15: result += 'F';break;
default: result += arr[i] % 16;
}
}
return result;
}
console.log(rgb(255, 255, 255)) // returns FFFFFF
console.log(rgb(255, 255, 300)) // returns FFFFFF
console.log(rgb(0,0,0)) // returns 000000
console.log(rgb(148, 0, 211)) // returns 9400D3