|
2 | 2 |
|
3 | 3 | module.exports = parse |
4 | 4 |
|
5 | | -var numberSign = 35 // '#' |
6 | | -var dot = 46 // '.' |
| 5 | +var search = /[#.]/g |
7 | 6 |
|
8 | 7 | // Create a hast element from a simple CSS selector. |
9 | 8 | function parse(selector, defaultTagName) { |
10 | 9 | var value = selector || '' |
11 | 10 | var name = defaultTagName || 'div' |
12 | 11 | var props = {} |
13 | | - var index = -1 |
14 | | - var length = value.length |
15 | | - var className |
16 | | - var type |
17 | | - var code |
| 12 | + var start = 0 |
18 | 13 | var subvalue |
19 | | - var lastIndex |
20 | | - |
21 | | - while (++index <= length) { |
22 | | - code = value.charCodeAt(index) |
23 | | - |
24 | | - if (!code || code === dot || code === numberSign) { |
25 | | - subvalue = value.slice(lastIndex, index) |
26 | | - |
27 | | - if (subvalue) { |
28 | | - if (type === dot) { |
29 | | - // eslint-disable-next-line max-depth |
30 | | - if (className) { |
31 | | - className.push(subvalue) |
32 | | - } else { |
33 | | - className = [subvalue] |
34 | | - props.className = className |
35 | | - } |
36 | | - } else if (type === numberSign) { |
37 | | - props.id = subvalue |
38 | | - } else { |
39 | | - name = subvalue |
40 | | - } |
| 14 | + var previous |
| 15 | + var match |
| 16 | + |
| 17 | + while (start < value.length) { |
| 18 | + search.lastIndex = start |
| 19 | + match = search.exec(value) |
| 20 | + subvalue = value.slice(start, match ? match.index : value.length) |
| 21 | + |
| 22 | + if (subvalue) { |
| 23 | + if (!previous) { |
| 24 | + name = subvalue |
| 25 | + } else if (previous === '#') { |
| 26 | + props.id = subvalue |
| 27 | + } else if (props.className) { |
| 28 | + props.className.push(subvalue) |
| 29 | + } else { |
| 30 | + props.className = [subvalue] |
41 | 31 | } |
42 | 32 |
|
43 | | - lastIndex = index + 1 |
44 | | - type = code |
| 33 | + start += subvalue.length |
45 | 34 | } |
46 | | - } |
47 | 35 |
|
48 | | - return { |
49 | | - type: 'element', |
50 | | - tagName: name, |
51 | | - properties: props, |
52 | | - children: [] |
| 36 | + if (match) { |
| 37 | + previous = match[0] |
| 38 | + start++ |
| 39 | + } |
53 | 40 | } |
| 41 | + |
| 42 | + return {type: 'element', tagName: name, properties: props, children: []} |
54 | 43 | } |
0 commit comments