FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Hard

ClassNames II

35mins

Implement a function classnames(...args) that conditionally joins CSS class names into a single string.

The function should:

  • Accept any number of arguments.
  • Handle strings, arrays, objects, and functions as input.
  • Include a class name if the value is truthy.
  • Recursively flatten arrays.
  • Evaluate functions and include their returned value if truthy.
  • Remove duplicate class names.

Example

classnames("btn", ["btn-primary", "active"], { disabled: false, hidden: true }, () => "dynamic"); // "btn btn-primary active hidden dynamic" classnames("a", "b", "a", ["c", "b"]); // "a b c"

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests