HEX for RGB using an iterator - better way than using .forEach?

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})`;
};
+4
source share
1 answer

Perhaps you can do the following:

function hex2rgb(h){
  return "rgb(" + [(h & 0xff0000) >> 16, (h & 0x00ff00) >> 8, h & 0x0000ff].reduce((p,c) => p+","+c) + ")";
}

console.log(hex2rgb(0xffffff));
console.log(hex2rgb(0x12abf0));
console.log(hex2rgb(0x000000));
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1685396/


All Articles