This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for JavaScript Coding Question on BFE.dev
125. implement classNames()

function classNames(...args) {
  let classes = [];
  
  args.forEach(arg => {
    if (typeof arg === 'string' || typeof arg === 'number') {
      classes.push(arg);
    } else if (Array.isArray(arg)) {
      classes.push(classNames(...arg));
    } else if (typeof arg === 'object' && arg !== null) {
      for (const key in arg) {
        if (Object.prototype.hasOwnProperty.call(arg, key) && arg[key]) {
          classes.push(key);
        }
      }
    }
  });
  
  return classes.join(' ');
}

Explanation:

  • The function takes in arbitrary number of arguments using the rest parameter syntax.
  • It initializes an empty array classes to hold the final class names.
  • It then loops through the arguments array using forEach() and checks the type of each argument using typeof operator.
  • If the argument is a string or number, it is added directly to classes array using push() method.
  • If the argument is an array, it calls classNames() recursively with the elements of the array as arguments using spread syntax (...arg), and adds the result to classes array.
  • If the argument is an object and not null, it loops through its enumerable keys using for-in loop, and checks if the key is a string and the value is truthy using hasOwnProperty() and arg[key] respectively. If both conditions are true, the key is added to classes array.
  • Finally, it joins all the elements of classes array into a single string using join(' ') method and returns it.