This proposal is predicated on the idea that space separated values inside the class attribute should be unique.
<p class='valueA valueB valueC'>...<\p>
I have been running into situations where I build complex objects on top of simpler ones. And many times I can't be sure if the simple object has certain values already set. So there are two choices—check the simple object for that value before adding, or just add the one I need.
Checking takes extra time and code for every string, like an unnecessary two-step process.
And blindly adding introduces the possibility of duplicate values, which, depending on the number of them, can lead to very messy html.
And just fundamentally, if class values should be unique, they should be managed that way.
Instead of...
func `class`(add value: String?, _ condition: Bool = true) -> Self
How about...
func `class`(insert value: String?, _ condition: Bool = true) -> Self
And then treat the underlying String like a Set while manipulating it.
So when you want to add a value, you don't have to worry about whether it exists or not. And no duplications. Changing the parameter label to insert
reinforces that notion.
Also, I added a version that takes variadic Optionals.
func `class`(insert values: String?..., if condition: Bool = true) -> Self
I use it in my own code and find it extremely flexible. You can write...
tag.class(insert: v)
tag.class(insert: optionalV)
tag.class(insert: v, if: condition)
tag.class(insert: optionalV, if: condition)
tag.class(insert: v, optionalV)
tag.class(insert: v, optionalV, if: condition)
tag.class(insert: v, optionalV, "anything", if: condition)
The only rub is having to put a parameter label where there was none. I chose if
to indicate the logic.
I won't take it personally if this seems a bit too far out on a limb. But it's really flexible and terse when you need to constantly add a few values here or there without the [ ]
. And it keeps with the theme of every other function that accepts an optional value and a Bool condition.
I also changed...
func `class`(insert values: [String], _ condition: Bool = true) -> Self
...to take an optional array. Again more flexibility and keeps with the theme of every other func. But I understand if it's a bridge too far.
func `class`(insert values: [String]?, _ condition: Bool = true) -> Self
Lastly, I added a guard
condition in...
func `class`(remove values: [String], _ condition: Bool = true) -> Self
I could be wrong, but I think the class
attribute can be deleted even if the condition
is false
I commented on my lines of code as well. Hopefully that makes things more clear.