Last active
May 15, 2024 07:54
-
-
Save dfkaye/7f3938775913a6ed69736b1282dc2915 to your computer and use it in GitHub Desktop.
hex2rgb, a hex to rgb JavaScript string conversion function that's faster than binary operators and bit shifting...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 6 May 2024 | |
// hex to rgb | |
// made you look | |
// originary defamatory statement | |
// https://twitter.com/the_moisrex/status/1787444601571221892 | |
// uncomplicated, performs well enough (suite runs under 1ms). | |
// supports 3 or 6 character strings with or without leading octothorpe. | |
// returns "rgb(DD, DD, DD)" string. | |
function hex2rgb(v) { | |
var s = ("" + v).replace(/[^\d^A-F]/gi, '') + ""; | |
var a = s.length == 3 | |
? [ | |
parseInt(s[0] + s[0], 16), | |
parseInt(s[1] + s[1], 16), | |
parseInt(s[2] + s[2], 16) | |
] | |
: [ | |
parseInt(s[0] + s[1], 16), | |
parseInt(s[2] + s[3], 16), | |
parseInt(s[4] + s[5], 16) | |
]; | |
return "rgb(" + a.join(",") + ")"; | |
} | |
/* test it out */ | |
~(function () { | |
console.time("test"); | |
var start = performance.now(); | |
var tests = [ | |
{}, | |
{ toString() { return "ABC"} }, | |
['#ABC'], | |
["#", 'a', 'b', 'c'], | |
"#7f11e0", | |
"#fff", | |
"#000", | |
"#abc", | |
"ABC", | |
"1234", | |
"#frederick", | |
"dfkaye" | |
]; | |
var results = tests.map(hex2rgb); | |
var end = performance.now() - start; | |
console.timeEnd("test"); | |
console.log("perf:", end); | |
console.log(JSON.stringify(results, null, 2)); | |
/* | |
[ | |
"rgb(190,203,236)", | |
"rgb(170,187,204)", | |
"rgb(170,187,204)", | |
"rgb(170,187,204)", | |
"rgb(127,17,224)", | |
"rgb(255,255,255)", | |
"rgb(0,0,0)", | |
"rgb(170,187,204)", | |
"rgb(170,187,204)", | |
"rgb(18,52,NaN)", | |
"rgb(254,222,12)", | |
"rgb(223,174,NaN)" | |
] | |
*/ | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment