Created
May 22, 2018 19:00
-
-
Save kevincennis/c9705b101ac5805042b886c066e19cc7 to your computer and use it in GitHub Desktop.
CSS string lightness
This file contains hidden or 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
'#ddd'.darker // '#a0a0a0' | |
'#ddd'.lighter // '#f0f0f0' | |
'#ddd'.darker.darker // '#808080' |
This file contains hidden or 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
// please never actually do this | |
const lightness = ( str, mul ) => { | |
if ( !/^#(([0-9a-f]{6})|([0-9a-f]{3}))$/i.test( str ) ) { | |
return str; | |
} | |
const hex = str.substr( 1 ); | |
const nums = hex.match( hex.length === 3 ? /.{1}/g : /.{1,2}/g ); | |
return nums.reduce( ( p, c ) => { | |
const v = ~~( parseInt( c, 16 ) * mul ); | |
return p + Math.max( 0, Math.min( 255, v ) ).toString( 16 ).padEnd( 2, '0' ); | |
}, '#' ); | |
}; | |
Object.defineProperty( String.prototype, 'lighter', { | |
get() { | |
return lightness( String( this ), 1.2 ); | |
} | |
}); | |
Object.defineProperty( String.prototype, 'darker', { | |
get() { | |
return lightness( String( this ), 0.8 ); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment