繁体   English   中英

使用迭代器将HEX转换为RGB - 比使用.forEach更好的方法?

[英]HEX to RGB using an iterator - better way than using .forEach?

我创建了一个相当难看的函数,用于将hex转换为rgb,我真的不喜欢我使用.forEach的方式以及在迭代之前定义空数组的需要。

我觉得应该有一个更好的办法来做这样的事情,我不知道吗? 我已经尝试过.reducemap和其他几个但我需要返回一个新的数组并推送给其他所有角色。

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

这是一个没有任何循环的简单解决方案:

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

如果您的问题更多是关于如何组织“成对”循环,您可以使用类似于python的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;
};

一旦完成,其余的都是微不足道的:

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

也许你可以这样做;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM