Skip to content

Instantly share code, notes, and snippets.

@granmoe
Last active May 9, 2017 01:43
Show Gist options
  • Save granmoe/f1a765d9f83c837fa593d043a3dddfc1 to your computer and use it in GitHub Desktop.
Save granmoe/f1a765d9f83c837fa593d043a3dddfc1 to your computer and use it in GitHub Desktop.
I saw this super simple, useful idea floating around in some projects and decided to implement the API myself instead of installing yet another "micro dependency." Plus, I can be more opinionated (assuming BEM, for example) when I use my own code.
export default function () {
let className = ''
let options = {}
const classNames = []
if (arguments.length > 1) {
className = arguments[0]
options = arguments[1]
classNames.push(className)
} else {
options = arguments[0]
}
Object.entries(options).forEach(([key, value]) => {
if (value) {
if (['-', '_'].includes(key[0])) {
classNames.push(className + key)
} else {
classNames.push(key)
}
}
})
return classNames.join(' ')
}
/* examples:
classnames('foo', { 'bar': returnsTrue(), 'baz': someFalseyValue, 'qux': (() => 1)() })
=== 'foo bar qux'
classnames('foo__bar', { '--baz': returnsTrue(), '--quz': someFalseyValue })
=== 'foo__bar foo__bar--baz'
classnames({ 'foo--bar': true, 'foo--baz': someFalseyValue })
=== 'foo--bar'
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment