Skip to content

Instantly share code, notes, and snippets.

@realiarthur
Created November 11, 2021 17:28
Show Gist options
  • Save realiarthur/37e3378eb06a9cf4a1c06722e2dcde51 to your computer and use it in GitHub Desktop.
Save realiarthur/37e3378eb06a9cf4a1c06722e2dcde51 to your computer and use it in GitHub Desktop.
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