[英]HEX to RGB using an iterator - better way than using .forEach?
我創建了一個相當難看的函數,用於將hex轉換為rgb,我真的不喜歡我使用.forEach
的方式以及在迭代之前定義空數組的需要。
我覺得應該有一個更好的辦法來做這樣的事情,我不知道嗎? 我已經嘗試過.reduce
, map
和其他幾個但我需要返回一個新的數組並推送給其他所有角色。
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.