Last active
November 27, 2023 11:33
-
-
Save syntax-punk/7f03b3a58d1c25666bc08e0b369342e5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| type ClassNameObject = { | |
| [key: string]: boolean; | |
| }; | |
| export function classnames(...values: (string | ClassNameObject | string[] | undefined)[]): string { | |
| const result = values | |
| .filter(Boolean) // Filter out falsy values | |
| .reduce<string[]>((classes, next) => { | |
| if (Array.isArray(next)) { | |
| // Handle arrays by recursively calling classnames | |
| classes.push(classnames(...next)); | |
| } else if (typeof next === 'object') { | |
| // Handle objects (ClassNameObject) using for...of with Object.entries | |
| for (const [key, value] of Object.entries(next)) { | |
| if (value) { | |
| classes.push(key); | |
| } | |
| } | |
| } else if (typeof next === 'string') { | |
| classes.push(next); | |
| } | |
| return classes; | |
| }, []) | |
| .join(' '); | |
| return result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment