Skip to content

Instantly share code, notes, and snippets.

@kevincennis
Created May 22, 2018 19:00
Show Gist options
  • Select an option

  • Save kevincennis/c9705b101ac5805042b886c066e19cc7 to your computer and use it in GitHub Desktop.

Select an option

Save kevincennis/c9705b101ac5805042b886c066e19cc7 to your computer and use it in GitHub Desktop.

Revisions

  1. kevincennis revised this gist May 22, 2018. 2 changed files with 2 additions and 2 deletions.
    2 changes: 0 additions & 2 deletions example.js
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,3 @@
    '#ddd'.darker // '#a0a0a0'

    '#ddd'.lighter // '#f0f0f0'

    '#ddd'.darker.darker // '#808080'
    2 changes: 2 additions & 0 deletions lightness.js
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    // please never actually do this

    const lightness = ( str, mul ) => {
    if ( !/^#(([0-9a-f]{6})|([0-9a-f]{3}))$/i.test( str ) ) {
    return str;
  2. kevincennis created this gist May 22, 2018.
    5 changes: 5 additions & 0 deletions example.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    '#ddd'.darker // '#a0a0a0'

    '#ddd'.lighter // '#f0f0f0'

    '#ddd'.darker.darker // '#808080'
    25 changes: 25 additions & 0 deletions lightness.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    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 );
    }
    });