Oasis's Cloud

一个人的首要责任,就是要有雄心。雄心是一种高尚的激情,它可以采取多种合理的形式。
—— 《一个数学家的辩白》

构建正则表达式


从 css 选择器开始

css 选择器的灵感来自正则表达式,简单易学,容易理解。所以我们先从最熟悉的 css 选择器开始。看看 css 选择其是如何进行匹配的。

在开始之前先设计我们要支持的选择器:

我们会构建一个 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
}