125. implement classNames()

Is this helpful ?

from all members: - accepted / - tried

If using React, you can set the prop className to add class name to an element, it is string so you can add multiple class names like this:

<p className="classname1 classname2">
  BFE.dev can help

When class names are dynamically generated, it becomes verbose.

  className={`classname1  ${shouldAddClassname2 ? 'classname2' : ''}`}>
  BFE.dev can help

classnames can help with this.

classNames() accepts arbitrary arguments, filter out the falsy values, and generate the final className string.

  1. string and number are used directly.
classNames('BFE', 'dev', 100) 
// 'BFE dev 100'
  1. other primitives are ignored.
  null, undefined, Symbol(), 1n, true, false
// ''
  1. Object's enumerable property keys are kept if the key is string and value is truthy. Array should be flattened.

const obj = new Map()
obj.cool = '!'

classNames({BFE: [], dev: true, is: 3}, obj) 
// 'BFE dev is cool'

classNames(['BFE', [{dev: true}, ['is', [obj]]]])
// 'BFE dev is cool'

Please implement your own classNames().


It is not the goal to reimplement the original package, so the spec might be a little different, please follow the above description.

Let's try to solve this problem within 10 mintues.