Skip to content

Instantly share code, notes, and snippets.

@syntax-punk
Last active November 27, 2023 11:33
Show Gist options
  • Select an option

  • Save syntax-punk/7f03b3a58d1c25666bc08e0b369342e5 to your computer and use it in GitHub Desktop.

Select an option

Save syntax-punk/7f03b3a58d1c25666bc08e0b369342e5 to your computer and use it in GitHub Desktop.
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