Last active
April 1, 2024 20:11
-
-
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
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
// 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