Skip to content

Instantly share code, notes, and snippets.

@ryanmorr
Last active April 1, 2024 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanmorr/386225a9afea421c4c1b9120d62ca716 to your computer and use it in GitHub Desktop.
Save ryanmorr/386225a9afea421c4c1b9120d62ca716 to your computer and use it in GitHub Desktop.
Generate a class name for a DOM element with a string, array, or object literal
// Courtesy of: https://github.com/jorgebucaran/hyperapp
function createClass(value) {
if (typeof value === 'string') {
return value;
}
let output = '';
if (Array.isArray(value)) {
for (let i = 0, len = value.length, tmp; i < len; i++) {
if ((tmp = createClass(value[i])) !== '') {
output += (output && ' ') + tmp;
}
}
} else {
for (const cls in value) {
if (value[cls]) {
output += (output && ' ') + cls;
}
}
}
return output;
}
// Usage:
createClass('foo'); //=> "foo"
createClass(['foo', 'bar']); //=> "foo bar"
createClass({foo: true, bar: false, baz: true}); //=> "foo baz"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment