I've created a rather ugly function for converting hex to rgb and I really don't like the way I've used .forEach
and the need for defining an empty array before the iteration.
I feel like there should be a better way for doing things like this that I'm not aware of? I've tried .reduce
, map
and a few others but I need to return a new array and push to 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})`;
};
Here's a simpler solution without any loops at all:
const rgba = (hex, alpha) => {
let clr = parseInt(hex.slice(1), 16),
rgb = [
(clr >> 16) & 0xFF,
(clr >> 8) & 0xFF,
(clr >> 0) & 0xFF
];
return `rgba(${rgb.join(', ')}, ${alpha})`;
};
If your question is more about how to organize a 'pairwise' loop, you can use a function similar to python's itertools.groupby
:
let groupBy = function*(iter, fn) {
let group = null,
n = 0,
last = {};
for (let x of iter) {
let key = fn(x, n++);
if (key === last) {
group.push(x);
} else {
if (group)
yield group;
group = [x];
}
last = key;
}
yield group;
};
Once this is done, the rest is trivial:
const rgba = (hex, alpha) => {
let pairs = [...groupBy(hex.slice(1), (_, n) => n >> 1)]
let rgb = pairs.map(x => parseInt(x.join(''), 16));
return `rgba(${rgb.join(', ')}, ${alpha})`;
};
Maybe you can do as 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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.