I have already written a working method, that can convert an array of rgb values to a hexadecimal color string:
/**
* @param {Number[]} arr Array with three entries (rgb: [0-255, 0-255, 0-255]).
* @return {String} Hex color as a string (rgb: '#000000' - '#ffffff').
*/
function arrToHex(arr) {
return '#' + arr
.map(v => ('0' + v.toString(16)).slice(-2))
.join('');
}
But I'm unsure whether this method is the best approach when it comes to efficiency. This method is called pretty often in my code.
Especially the part with ('0' + v.toString(16)).slice(-2) (to get a double hexadecimal) seems too complicated to me. Can this be done better? Is this functional approach even the best?
Performance evaluations:
Results show average seconds calculated by console.time if run with Google Chrome v83 (64bit, Linux). Ordered from best to worst.
Iterative and lookup table solution by selbie: (~1.1sec)
const hextable = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
function arrToHex(arr) {
let s = '#';
for (let i = 0; i < arr.length; i++) {
s += hextable[(arr[i] / 16) | 0];
s += hextable[arr[i] % 16 | 0];
}
return s;
}
console.time('arrToHex');
for (var r = 0; r < 256; r++)
for (var g = 0; g < 256; g++)
for (var b = 0; b < 256; b++) {
arrToHex([r, g, b]);
}
console.timeEnd('arrToHex');
Iterative and no lookup table solution by selbie: (~1.8sec)
function arrToHex(arr) {
let s = '#';
for (let i = 0; i < arr.length; i++) {
s += ((arr[i] / 16) | 0).toString(16);
s += ((arr[i] % 16) | 0).toString(16);
}
return s;
}
console.time('arrToHex');
for (var r = 0; r < 256; r++)
for (var g = 0; g < 256; g++)
for (var b = 0; b < 256; b++) {
arrToHex([r, g, b]);
}
console.timeEnd('arrToHex');
Non-iterative solution by [deleted]: (~2.6sec)
function arrToHex(arr) {
const rgb = arr[2] | (arr[1] << 8) | (arr[0] << 16);
return '#' + rgb.toString(16).padStart(6, '0');
}
console.time('arrToHex');
for (var r = 0; r < 256; r++)
for (var g = 0; g < 256; g++)
for (var b = 0; b < 256; b++) {
arrToHex([r, g, b]);
}
console.timeEnd('arrToHex');
My bad functional approach: (~6.5sec)
function arrToHex(arr) {
return '#' + arr
.map(v => ('0' + v.toString(16)).slice(-2))
.join('');
}
console.time('arrToHex');
for (var r = 0; r < 256; r++)
for (var g = 0; g < 256; g++)
for (var b = 0; b < 256; b++) {
arrToHex([r, g, b]);
}
console.timeEnd('arrToHex');
.toString(16).padStart(2,'0')is another way around to make sure you have 2 hex-digits, other than that, your code looks pretty viable#rgbor#rrggbbor#rrggbbaaorrgb(r,g,b)orrgba(r,g,b,a), and that the conversion will be done by native code, rather than javascript, is there any real reason to do the conversion at all? Without knowing more, I wouldn't discount simplifying this whole method to the roughly equivalent:reurn( 'rgb(' +r+ ',' +g+ ',' +b+ ')' );rgbfunction in CSS, but this isn't helpful in my use case.