I created a pretty ugly function to convert hex to rgb, and I really dislike the way I used .forEachand the need to define an empty array before iterating.
I feel that there must be a better way to do things that I donβt know about? I tried .reduce, mapand several others, but I need to return a new array and click on it every other character.
const rgba = (hex, alpha) => {
const pairs = [...hex.slice(1, hex.length)];
const rgb = [];
pairs.forEach((char, index) => {
if (index % 2 !== 0) return;
const pair = `${char}${pairs[index + 1]}`;
rgb.push(parseInt(pair, 16));
});
return `rgba(${rgb.join(', ')}, ${alpha})`;
};
source
share