Skip to curriculum
Jump to the editor

17.3. Build a class string from conditions

Easy
Topics
10–20 min

Components 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

JAVASCRIPT
function classNames(...args) // returns a string

Each 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

  1. Strings add their names. A string may hold several names separated by whitespace; extra spaces, tabs and new lines never reach the result.
  2. Numbers other than 0 and NaN add their text (3 adds "3").
  3. Falsy values (false, null, undefined, 0, NaN, "") add nothing. true, functions and symbols add nothing either.
  4. Arrays are read item by item with the same rules, nested at any depth. Holes are skipped.
  5. 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.
  6. 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.
  7. The arguments are not changed.

Examples

JAVASCRIPT
classNames("btn", { "btn-primary": isMain, "is-loading": loading });
// isMain true, loading false: "btn btn-primary"
JAVASCRIPT
classNames("card  wide", ["shadow", ["rounded"]], 0, null, 2);
// "card wide shadow rounded 2"
JAVASCRIPT
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 classNames from classnames.js.
  • Objects other than arrays are all read as key-value maps (a Date has no own keys, so it adds nothing).
  • String.prototype.split and Set are fine to use.

Hints

  1. One function that handles any single value, and calls itself for array items, covers every nesting depth. What does it do for each type?
  2. 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
Back to the question
Loading the editor…