构建正则表达式
从 css 选择器开始
css 选择器的灵感来自正则表达式,简单易学,容易理解。所以我们先从最熟悉的 css 选择器开始。看看 css 选择其是如何进行匹配的。
在开始之前先设计我们要支持的选择器:
- 标签选择器 div
- class 选择器 .cls
- id 选择器 #ident
- 子元素选择器 parent child
我们会构建一个 select 方法,支持传入元素节点,以及选择器:select(document.body, ‘div’)
const select = (root, selector) => {
// 由于选择器支持子元素,并且是一层一层的,
const selectors = selector.split(' ').filter(s => s.length > 0)
return firstMatch(root, selectors)
}
const firstMatch = (node, selectors) => {
if(node.type !== 'tag') {
return null
}
if(matchHere(node, selectors[0])) {
if(selectors.length == 1) {
return node
}
return firstChildMatch(node, selectors.slice(1))
}
return firstChildMatch(node, selectors)
}
const matchHere = () => {
}
const firstChildMatch = (node, selectors) => {
for(const child of node.children) {
const match = firstMatch(child, selectors)
if(match) {
return match
}
}
return null
}