125. implement classNames()

JavaScript
Is this helpful ?

medium  - 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:

BFE.dev can help

When class names are dynamically generated, it becomes verbose.

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.
classNames(
  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().

note

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 minutes.

Discuss(35)