This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
78. convert HEX color to RGBA
Here's one possible solution in JavaScript:
function hexToRgb(hex) {
// Remove any leading "#" from the hex code
hex = hex.replace(/^#/, '');
// Validate the input: it should be either 3 or 6 hex digits
if (!/^(?:[0-9a-fA-F]{3}){1,2}$/.test(hex)) {
throw new Error('Invalid hex code');
}
// Convert a 3-digit hex code to a 6-digit one by duplicating each digit
if (hex.length === 3) {
hex = hex.split('').map(x => x + x).join('');
}
// Convert the hex code to RGB values (as integers)
const r = parseInt(hex.substr(0, 2), 16);
const g = parseInt(hex.substr(2, 2), 16);
const b = parseInt(hex.substr(4, 2), 16);
// Round the alpha value to 2 decimal places (if needed)
const alpha = Math.round((1) * 100) / 100;
// Return the RGB values as a functional notation string
return `rgba(${r},${g},${b},${alpha})`;
}
Here's how you can use this function:
console.log(hexToRgb('#fff')); // 'rgba(255,255,255,1)'
console.log(hexToRgb('#00aaff')); // 'rgba(0,170,255,1)'
console.log(hexToRgb('#123abc')); // 'rgba(18,58,188,1)'
console.log(hexToRgb('#abc')); // Error: Invalid hex code
console.log(hexToRgb('#abc1234')); // Error: Invalid hex code