UNPKG

@trellixio/roaster-coffee

Version:
62 lines (61 loc) 1.8 kB
/** * Takes an arbitrary number of arguments and returns a space-separated string of class names. * Arguments can be strings, numbers, arrays, or objects. Arrays can be nested and will be flattened. * Objects should have keys as class names and values as booleans, indicating whether the class should be included. * * @remarks * This function can be used to simplify the process of building class names in a dynamic and conditional way. * * @param args - The input arguments to be processed for class names. * @returns A space-separated string of class names. * * @example * ```typescript * // returns 'class1 class2' * classNames('class1', 'class2'); * ``` * * @example * ```typescript * // returns 'class1 class2' * classNames('class1', ['class2']); * ``` * * @example * ```typescript * // returns 'class1 class2' * classNames('class1', { class2: true }); * ``` * * @example * ```typescript * // returns 'class1 class2 class3 class4' * classNames('class1', ['class2', { class3: true }], { class4: true }); * ``` */ export function classNames(...args) { const classes = []; for (let i = 0; i < args.length; i += 1) { const arg = args[i]; if (!arg) continue; const argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg) && arg.length) { const inner = classNames(...arg); if (inner) { classes.push(inner); } } else if (argType === 'object') { Object.keys(arg).map((key) => { if (arg[key]) classes.push(key); return ''; }); } } return classes.join(' '); }