Created
January 26, 2018 01:05
-
-
Save jhnsnc/e8b83e519e8b153d697d208fcad6910a to your computer and use it in GitHub Desktop.
Utility class for adding/removing class names by chaining function calls rather than doing manual string manipulation
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
/** | |
* Conditionally add/remove classes and render the result to a class list string | |
* | |
* @param {...string} initialClasses - initial class names to add | |
*/ | |
export class ClassNames { | |
constructor(...initialClasses) { | |
this.arrClasses_ = initialClasses; | |
this.breakUpSpaces_(); | |
return this; | |
} | |
breakUpSpaces_() { | |
this.arrClasses_.slice().forEach(className => { // slice a copy so iteration doesn't stop short | |
if (className.indexOf(' ') >= 0) { | |
var idx = this.arrClasses_.indexOf(className); | |
this.arrClasses_.splice.apply(this.arrClasses_, [idx, 1].concat(className.split(' '))); | |
} | |
}); | |
} | |
add(strClass) { | |
var trimmed = strClass.trim(); | |
if (this.arrClasses_.indexOf(trimmed) < 0 && trimmed.length) { | |
this.arrClasses_.push(trimmed); | |
this.breakUpSpaces_(); | |
} | |
return this; | |
} | |
addIf(strClass, condition) { | |
return condition ? this.add(strClass) : this; | |
} | |
remove(strClass) { | |
const idx = this.arrClasses_.indexOf(strClass.trim()); | |
if (idx >= 0) { | |
this.arrClasses_.splice(idx, 1); | |
this.breakUpSpaces_(); | |
} | |
return this; | |
} | |
removeIf(strClass, condition) { | |
return condition ? this.remove(strClass) : this; | |
} | |
toString() { | |
return this.arrClasses_.join(' '); | |
} | |
get [Symbol.toStringTag]() { | |
return 'ClassNames'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage: