This repository was archived by the owner on Jan 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
61 lines (50 loc) · 1.29 KB
/
Copy pathindex.js
File metadata and controls
61 lines (50 loc) · 1.29 KB
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
60
61
const {CssSelectorParser} = require('css-selector-parser')
const parser = new CssSelectorParser()
parser.registerNestingOperators('>', '+', '~')
parser.registerAttrEqualityMods('^', '$', '*', '~', '|')
parser.registerSelectorPseudos('not')
const complexity = selector => {
if (typeof selector !== 'string' || selector.trim() === '') {
throw new Error(
`selector must be a string, got ${typeof selector} (${JSON.stringify(
selector
)})`
)
}
let rule
// Catch any broken CSS selector (see tests)
try {
rule = parser.parse(selector)
} catch (error) {
throw new Error(
`Invalid selector. Check the syntax validity of '${selector}'`
)
}
let total = 0
while ((rule = rule.rule)) {
if (rule.tagName && rule.tagName !== '*') {
total += 1
}
if (rule.id) {
total += 1
}
if (rule.classNames) {
total += rule.classNames.length
}
if (rule.attrs) {
total += rule.attrs
.map(attr => (attr.value ? 2 : 1))
.reduce((total, attributeCount) => total + attributeCount)
}
if (rule.pseudos) {
total += rule.pseudos
.filter(pseudo => pseudo.name !== '')
.map(pseudo =>
pseudo.name === 'not' ? complexity(parser.render(pseudo.value)) : 1
)
.reduce((total, pseudoCount) => total + pseudoCount)
}
}
return total
}
module.exports = complexity