เราต้องเขียนฟังก์ชัน JavaScript ที่รับสี RGB และคืนค่าการแทนค่า hexadecimal
ฟังก์ชันควรรับออบเจกต์ที่มีตัวเลขสามตัวแทนค่าของสีแดง เขียว และน้ำเงินตามลำดับ
ตัวอย่าง:
rgbToHex(0, 128, 192) should return '#0080C0'
โค้ดสำหรับเรื่องนี้จะเป็น:
const rgbColor = {
red: 0,
green: 51,
blue: 155
}
function rgbToHex({
red: r,
green: g,
blue: b
}) {
const prefix = '#';
const hex = prefix + ((1 << 24) + (r << 16) + (g << 8) + b)
.toString(16)
.slice(1);
return hex;
}
console.log(rgbToHex(rgbColor));
ผลลัพธ์บนคอนโซล:
#00339b