This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
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
classesto hold the final class names. - It then loops through the arguments array using
forEach()and checks the type of each argument usingtypeofoperator. - If the argument is a string or number, it is added directly to
classesarray usingpush()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 toclassesarray. - If the argument is an object and not null, it loops through its enumerable keys using
for-inloop, and checks if the key is a string and the value is truthy usinghasOwnProperty()andarg[key]respectively. If both conditions are true, the key is added toclassesarray. - Finally, it joins all the elements of
classesarray into a single string usingjoin(' ')method and returns it.