CodePark/ problems / classnames
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Parsing and building strings

classnames

easyabout 12 minutes in an interview

Implement classNames(...args), like the popular classnames package that builds a CSS class attribute. It returns one string of class names separated by single spaces.

Each argument can be:

  • a string: added as a class name. Strings never contain spaces.
  • a number: added as its string form, so 12 adds "12".
  • an object: each key whose value is truthy is added, in key order. Truthy means the value counts as true in an if.
  • an array: its items are handled by these same rules, at any depth.
  • falsy values (false, null, undefined, 0, "") are skipped. true is skipped too.

Duplicates: each class appears once, at the position where it first appeared. A falsy value in an object only skips that key. It never removes a class added earlier.

With nothing to include, return "".

Input: classNames('btn', { active: true, disabled: false }) Output: 'btn active'
Input: classNames(['a', ['b', { c: 1 }]], null, 0, 'a') Output: 'a b c'falsy values skipped, the second 'a' dropped