call(back)

Implement classNames

Implement classNames(...args), the utility that conditionally joins CSS class names.

classNames("foo", "bar");                      // "foo bar"
classNames("foo", { bar: true, baz: false });  // "foo bar"
classNames({ "foo-bar": true });               // "foo-bar"
classNames("a", ["b", { c: true, d: false }]); // "a b c"
classNames(null, false, "bar", 0, { baz: null }, ""); // "bar"
  • Strings and numbers are added as they are; 0 is falsy and skipped like every other falsy value.
  • An object adds each key whose value is truthy.
  • Arrays are flattened recursively, by the same rules.
  • The result has single spaces between names and none at either end.

Hints

Hint 1

One recursive collect(arg) that pushes onto a shared list handles every shape; arrays just call it on each item.

Hint 2

Check falsiness first and strings or numbers second, so the object branch only ever sees real objects.

Asked at

Similar Problems5