The task is to implement a function to add class names.
The boilerplate code
function classNames(...args) {
// your code here
}
The function should combine different kinds of input into one space-separated string.
Create a variable to store the result
const result = []
If the argument is not a string, number, array, or object, skip it.
const process = (arg) => {
if (!arg) return;
If the argument is a string or a number, push is immediately
if (typeof arg === 'string' || typeof arg === 'number') {
result.push(arg);
return;
}
If the argument is an array, loop through it again (recursion)
if (Array.isArray(arg)) {
arg.forEach(process);
return;
}
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);
}
}
}
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(' ');
}
That's all folks!
Top comments (0)