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 usingtypeof
operator. - If the argument is a string or number, it is added directly to
classes
array 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 toclasses
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 usinghasOwnProperty()
andarg[key]
respectively. If both conditions are true, the key is added toclasses
array. - Finally, it joins all the elements of
classes
array into a single string usingjoin(' ')
method and returns it.