Skip to content

Instantly share code, notes, and snippets.

@VitorLuizC
Last active March 20, 2018 13:01
Show Gist options
  • Select an option

  • Save VitorLuizC/33521770b8b5fd0d43f7d58e0cd640cf to your computer and use it in GitHub Desktop.

Select an option

Save VitorLuizC/33521770b8b5fd0d43f7d58e0cd640cf to your computer and use it in GitHub Desktop.
type ClassNameObject = { [key: string]: boolean };
type ClassNameList = Array<(string | ClassNameObject)>;
type ClassNameArguments = (string | ClassNameObject | ClassNameList);
type ClassNameEntry = [keyof ClassNameObject, ClassNameObject[keyof ClassNameObject]];
const isTruthyEntryValue = ([ , value ]: ClassNameEntry) => Boolean(value);
const getEntryKey = ([ key ]: ClassNameEntry) => key;
const toClassNames = ( value ): string | Array<string> => {
if ( typeof value === 'string' )
return value;
if ( Array.isArray( value ) && value.length )
return [].concat( ...value.map( toClassNames ) );
if ( value && typeof value === 'object' )
return Object.entries( value ).filter( isTruthyEntryValue ).map( getEntryKey );
}
const getClassNames = ( ...values: Array<ClassNameArguments> ) => (
[ ].concat(
...values.map( toClassNameList )
).join( ' ' );
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment