17.3. Build a class string from conditions
Topics
This question is in
17. DOM: changing the page and eventsComponents build their class attribute from state: a button is always btn, is btn-primary when it is the main action, is-loading while a request runs and is-disabled when the form is invalid. Writing that with string concatenation and ternaries leaves double spaces, stray undefineds and repeated names. A small classNames helper takes the pieces and the conditions and returns one clean string.
Write classNames in classnames.js.
Signature
function classNames(...args) // returns a stringEach argument can be a string, a number, an array or an object. The result is the class names joined by single spaces, or "" when there are none.
Requirements
- Strings add their names. A string may hold several names separated by whitespace; extra spaces, tabs and new lines never reach the result.
- Numbers other than
0andNaNadd their text (3adds"3"). - Falsy values (
false,null,undefined,0,NaN,"") add nothing.true, functions and symbols add nothing either. - Arrays are read item by item with the same rules, nested at any depth. Holes are skipped.
- Objects: for each own key, a truthy value turns the name (or names, if the key holds several) on, and a falsy value turns it off, removing it if an earlier argument added it.
- Arguments are read left to right. Each name appears once, at the position where it was first turned on; a name turned off and on again goes to the end.
- The arguments are not changed.
Examples
classNames("btn", { "btn-primary": isMain, "is-loading": loading });
// isMain true, loading false: "btn btn-primary"classNames("card wide", ["shadow", ["rounded"]], 0, null, 2);
// "card wide shadow rounded 2"classNames("tab active", { active: false }); // "tab"
classNames("a b", "a", { b: true }); // "a b": no repeats
classNames(); // ""Environment
- Plain JavaScript; the tests call the global
classNamesfromclassnames.js. - Objects other than arrays are all read as key-value maps (a
Datehas no own keys, so it adds nothing). String.prototype.splitandSetare fine to use.
Hints
- One function that handles any single value, and calls itself for array items, covers every nesting depth. What does it do for each type?
- Which built-in collection already keeps one copy of each value in the order you added them?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it