เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้สีฐานสิบหกเป็นอินพุตเดียวเท่านั้น
ฟังก์ชันของเราควรหาสีเสริมสำหรับสีที่ป้อนเข้ามา
นี่คือคู่อินพุตและเอาต์พุตบางส่วน -
getComplementaryColor('#142814') = '#ebd7eb';
getComplementaryColor('#ffffff') = '#000000';
getComplementaryColor('#3399ff') = '#cc6600'; ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
const str1 = '#142814';
const str2 = '#ffffff';
const str3 = '#3399ff';
const getComplementaryColor = (color = '') => {
const colorPart = color.slice(1);
const ind = parseInt(colorPart, 16);
let iter = ((1 << 4 * colorPart.length) - 1 - ind).toString(16);
while (iter.length < colorPart.length) {
iter = '0' + iter;
};
return '#' + iter;
};
console.log(getComplementaryColor(str1));
console.log(getComplementaryColor(str2));
console.log(getComplementaryColor(str3)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
#ebd7eb #000000 #cc6600