Skip to content

Instantly share code, notes, and snippets.

@mr21
Created March 10, 2019 02:37
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 mr21/4f675ed404bfb20e36af0fb6191a1187 to your computer and use it in GitHub Desktop.
Save mr21/4f675ed404bfb20e36af0fb6191a1187 to your computer and use it in GitHub Desktop.
const Color = {
split( col ) {
switch ( col[ 0 ] ) {
case "r": return ( col[ 3 ] === "a"
? Color._rgbaExtract
: Color._rgbExtract )( col );
case "#": return ( col.length < 6
? Color._hex3Extract
: Color._hex6Extract )( col );
}
},
isDark( col ) {
const [ r, g, b ] = Color.split( col );
return ( r + g + b ) / 3 < 128;
},
// private:
_rgbExtract( col ) {
const rgb = col.substr( col.indexOf( "(" ) + 1 ).split( "," );
rgb[ 0 ] = parseInt( rgb[ 0 ] );
rgb[ 1 ] = parseInt( rgb[ 1 ] );
rgb[ 2 ] = parseInt( rgb[ 2 ] );
return rgb;
},
_rgbaExtract( col ) {
const rgb = Color._rgbExtract( col );
rgb[ 3 ] = parseFloat( rgb[ 3 ] );
return rgb;
},
_hex6Extract( col ) {
return [
parseInt( col.substr( 1, 2 ), 16 ),
parseInt( col.substr( 3, 2 ), 16 ),
parseInt( col.substr( 5, 2 ), 16 ),
];
},
_hex3Extract( col ) {
const r = parseInt( col.substr( 1, 1 ), 16 ),
g = parseInt( col.substr( 2, 1 ), 16 ),
b = parseInt( col.substr( 3, 1 ), 16 );
return [
r * 16 + r,
g * 16 + g,
b * 16 + b,
];
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment