Skip to content

Instantly share code, notes, and snippets.

@luismichel
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luismichel/11bddd7a5eef8b0184ca to your computer and use it in GitHub Desktop.
Save luismichel/11bddd7a5eef8b0184ca to your computer and use it in GitHub Desktop.
This method reduces color strings to a minified version, e.g. '#FF00FF' outputs '#F0F', 'rgb(255, 0, 255)' also outputs '#F0F'.
function minifyColor(stringColor) {
var rgb, slicedString, hexString;
if(stringColor.indexOf('rgb') !== -1) {
slicedString = stringColor.slice(stringColor.indexOf('(') +1, stringColor.indexOf(')'));
rgb = slicedString.split(',');
var hex = rgb.map(componentToHex);
hexString = '#'+hex[0]+hex[1]+hex[2];
} else {
hexString = stringColor;
}
return reduceHex(hexString);
}
function componentToHex(c) {
if( typeof c === 'string') c = parseInt(c);
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function reduceHex(hexString) {
var isValid = true;
var hexArray = hexString.slice(1).match(/.{1}./g);
var result = '#';
hexArray.forEach(function(segment) {
if(segment.charAt(0) === segment.charAt(1))
result += segment.charAt(0);
else
isValid = false;
});
return (isValid) ? result : hexString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment