DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 118

The task is to implement a function to add class names.

The boilerplate code

function classNames(...args) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

The function should combine different kinds of input into one space-separated string.

Create a variable to store the result

const result = []
Enter fullscreen mode Exit fullscreen mode

If the argument is not a string, number, array, or object, skip it.

const process = (arg) => {
    if (!arg) return;
Enter fullscreen mode Exit fullscreen mode

If the argument is a string or a number, push is immediately

if (typeof arg === 'string' || typeof arg === 'number') {
      result.push(arg);
      return;
    }

Enter fullscreen mode Exit fullscreen mode

If the argument is an array, loop through it again (recursion)

if (Array.isArray(arg)) {
      arg.forEach(process);
      return;
    }
Enter fullscreen mode Exit fullscreen mode

If the argument is an object, check each key's value


    if (typeof arg === 'object') {
      for (const key in arg) {
        if (arg[key]) {
          result.push(key);
        }
      }
    }
Enter fullscreen mode Exit fullscreen mode

The final code

function classNames(...args) {
  // your code here
  const result = [];

  const process = (arg) => {
    if(!arg) return;

    if(typeof arg === 'string' || typeof arg === "number") {
      result.push(arg);
      return;
    }
    if(Array.isArray(arg)) {
      arg.forEach(process);
      return;
    }
    if(typeof arg === 'object') {
      for(const key in arg) {
        if(arg[key]) {
          result.push(key);
        }
      }
    }
  }
  args.forEach(process);

  return result.join(' ');
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)