Last active
August 29, 2015 14:25
-
-
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'.
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
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