Created
November 11, 2021 17:28
-
-
Save realiarthur/37e3378eb06a9cf4a1c06722e2dcde51 to your computer and use it in GitHub Desktop.
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
interface ClassObject { | |
[className: string]: boolean | undefined | |
} | |
const addClass = ( | |
collection: string, | |
className?: string, | |
statement: boolean = false | |
): string => { | |
if (className === undefined || className === '' || !statement) { | |
return collection | |
} | |
if (collection === '') { | |
return className | |
} | |
return `${collection} ${className}` | |
} | |
/** | |
* Function for classnames concatenation | |
* @param args string or objects to conatenate | |
* @returns string with all truely classnames | |
*/ | |
const cx = (...args: Array<string | ClassObject | undefined>): string => { | |
return args.reduce<string>((computedClassName, currentArgument) => { | |
if (typeof currentArgument === 'object') { | |
return addClass( | |
computedClassName, | |
Object.entries(currentArgument).reduce( | |
(objectClassName, classObjectArray) => { | |
return addClass(objectClassName, ...classObjectArray) | |
}, | |
'' | |
), | |
true | |
) | |
} | |
return addClass(computedClassName, currentArgument, true) | |
}, '') | |
} | |
export default cx |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment