Class names
Implement classNames(...args), like the classnames library. Strings and numbers are kept. In an object, a key is kept when its value is truthy. Arrays are flattened at any depth. Everything else (false, null, undefined, 0, an empty string) is ignored. Return the kept names joined by one space.
Start from
function classNames(...args) {
// Return the truthy class names joined by a space.
}Hints
Each hint gives away a little more. Open one only when you need it.
Hint 1
Handle four cases in order: falsy (skip), string or number (keep), array (recurse), object (keep the keys with truthy values).
Hint 2
For an array, call classNames(...array) and keep the result when it is not empty.
Solution
From here on the page gives the method away. If you are still solving, go back to the hints.
JavaScript
function classNames(...args) {
const names = [];
for (const arg of args) {
if (!arg) continue;
if (typeof arg === "string" || typeof arg === "number") names.push(arg);
else if (Array.isArray(arg)) {
const inner = classNames(...arg);
if (inner) names.push(inner);
} else if (typeof arg === "object") {
for (const key of Object.keys(arg)) if (arg[key]) names.push(key);
}
}
return names.join(" ");
}What an interviewer looks for
Every React codebase has this helper. It checks type handling and recursion without any algorithm knowledge.