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


i've created rather ugly function converting hex rgb , don't way i've used .foreach , need defining empty array before iteration.

i feel there should better way doing things i'm not aware of? i've tried .reduce, map , few others need return new array , push 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})`; }; 

maybe can follows;

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));


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -