-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (49 loc) · 1.59 KB
/
index.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
47
48
49
50
51
52
53
54
55
56
57
58
59
const wildcard = '9007199254740991' // this will be injected as placeholder while calculating, before returning the classname we will remove those numbers
const is = (val, type) => {
if (typeof val === 'function' && type === 'function') {
return true
} else {
const objectType = Object.prototype.toString.call(val)
return !!objectType.slice(8,(objectType.length - 1)).match(new RegExp(type, 'gi'))
}
}
const dashify = (str = '') => {
if (typeof str !== 'string') return str
return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()
}
const removeNotSupportedTypes = val => {
return is(val, 'array|string|object')
}
const handleBlocks = (block, val) => {
if (is(val, 'string') && val.length > 0) {
return `${block}__${val}`
} else {
return val
}
}
const handleModifiers = (block, val) => {
if(is(val, 'array')) {
return val.length === 0 ? wildcard : val.map(a => `${block}--${a}`)
}
if(is(val, 'object')) {
const keys = Object.keys(val)
return keys.length === 0 ? wildcard : Object.keys(val).map(key => {
if(is(val[key], 'boolean')) {
return !!val[key] ? `${block}--${dashify(key)}` : wildcard
} else {
return `${block}--${dashify(key)}-${dashify(val[key])}`
}
})
}
if(is(val, 'string')) {
return val.length === 0 ? wildcard : val
}
return val
}
module.exports = block => (...args) => (args
.filter(removeNotSupportedTypes)
.map(handleBlocks.bind(null, block))
.map(handleModifiers.bind(null, block))
.join(' ')
.replace(/,/g, ' ') || block
).replace(new RegExp(wildcard, 'g'),'').trim()