-
Notifications
You must be signed in to change notification settings - Fork 0
/
classNames.js
46 lines (36 loc) · 1.33 KB
/
classNames.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const classNames = (...args) => {
const classArray = [];
args.forEach((classItem) => {
if (!classItem) return;
const type = typeof classItem;
if (type == 'string' || type == 'number') {
classArray.push(classItem);
return;
}
if(Array.isArray(classItem)) {
classArray.push(classNames(...classItem));
return;
}
if(type == 'object') {
for(const key in classItem) {
if(Object.hasOwn(classItem, key) && classItem[key]) {
classArray.push(key)
}
}
return;
}
})
classArray.join(" ");
}
console.log(classNames("foo", "bar")); // => 'foo bar'
console.log(classNames("foo", { bar: true })); // => 'foo bar'
console.log(classNames({ "foo-bar": true })); // => 'foo-bar'
console.log(classNames({ "foo-bar": false })); // => ''
console.log(classNames({ foo: true }, { bar: true })); // => 'foo bar'
console.log(classNames({ foo: true, bar: true })); // => 'foo bar'
// lots of arguments of various types
console.log(
classNames("foo", { bar: true, duck: false }, "baz", { quux: true })
); // => 'foo bar baz quux'
// other falsy values are just ignored
console.log(classNames(null, false, "bar", undefined, 0, 1, { baz: null }, "")); // => 'bar 1'