Created
June 16, 2020 10:03
-
-
Save zorgick/cb0a584fe4ecf23c9a81901290766a40 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
/** | |
* This function accepts array of strings or strings or both | |
* all empty or falsy values are omitted | |
* returns a string of classes | |
*@example | |
// 1) simple use case: single argument - array of strings | |
stringifyClasses([ | |
styles.day, | |
isPassive && styles.dayPassive, | |
disabled && styles.dayDisabled, | |
!isPassive && isToday && styles.dayToday, | |
isStartOfWeek && styles.dayStartOfWeek, | |
isEndOfWeek && styles.dayEndOfWeek, | |
isStartOfMonth && styles.dayStartOfMonth, | |
isEndOfMonth && styles.dayEndOfMonth, | |
]) | |
// 2) simple use case: multiple arguments - variadic strings | |
stringifyClasses( | |
styles.day, | |
isPassive && styles.dayPassive, | |
disabled && styles.dayDisabled, | |
!isPassive && isToday && styles.dayToday, | |
isStartOfWeek && styles.dayStartOfWeek, | |
isEndOfWeek && styles.dayEndOfWeek, | |
isStartOfMonth && styles.dayStartOfMonth, | |
isEndOfMonth && styles.dayEndOfMonth, | |
) | |
// 3) complex use case: multiple mixed arguments - variadic strings + variadic arrays | |
stringifyClasses( | |
styles.day, | |
isPassive && styles.dayPassive, | |
[ | |
disabled && styles.dayDisabled, | |
[ !isPassive && [ isToday && styles.dayToday ] ], // multiple nesting is allowed (max 5 levels) | |
isStartOfWeek && styles.dayStartOfWeek, | |
isEndOfWeek && styles.dayEndOfWeek | |
], | |
isStartOfMonth && styles.dayStartOfMonth, | |
isEndOfMonth && styles.dayEndOfMonth, | |
) | |
// 4) classNames prop provided: apply classNames or a default class | |
stringifyClasses( | |
classNames || styles.day, | |
) | |
// 5) optional block of classes case: removes whole block of classes if condition is falsy | |
stringifyClasses( | |
styles.day, | |
isPassive && styles.dayPassive, | |
props.disabled && [ | |
styles.dayDisabled, | |
[ !isPassive && [ isToday && styles.dayToday ] ], | |
isStartOfWeek && styles.dayStartOfWeek, | |
isEndOfWeek && styles.dayEndOfWeek | |
], | |
isStartOfMonth && styles.dayStartOfMonth, | |
isEndOfMonth && styles.dayEndOfMonth, | |
) | |
*/ | |
export function stringifyClasses<T extends unknown[]>(...classesArray: T) { | |
return classesArray.flat(5).filter(Boolean).join(' ') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment