Skip to content

Instantly share code, notes, and snippets.

@alanthai
Last active August 26, 2019 07:46
Show Gist options
  • Save alanthai/cfc97a3d9afffb3169a0 to your computer and use it in GitHub Desktop.
Save alanthai/cfc97a3d9afffb3169a0 to your computer and use it in GitHub Desktop.
Converts color hex to decimal
function toHex(n: number) {
return ('0' + n.toString(16)).slice(-2);
}
// ES6
function hexToRGB(code) {
const [r, g, b] = code.replace('#', '')
.match(/../g).map((hex) => parseInt(hex, 16));
return {r, g, b};
}
function rgbToHex({r, g, b}) {
return [r, g, b].map(toHex).reduce((acc, c) => acc + c, '#');
}
// ES5
function hexToRGB(code) {
var c = code.replace('#', '')
.match(/../g).map(function(hex) {return parseInt(hex, 16)});
return {r: c[0], g: c[1], b: [2]};
}
function rgbToHex(color) {
return ['r', 'g', 'b']
.map(toHex)
.reduce(function(acc, c) { return acc + color[c]; }, '#');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment