diff --git a/lib/filter.js b/lib/filter.js index d8e13d5..be30e15 100644 --- a/lib/filter.js +++ b/lib/filter.js @@ -57,8 +57,7 @@ function searchElement(entry, options) { res.push(node); // Do not push child nodes if matched else if (list = treeAdapter.getChildNodes(node)) - for (const n of list) - queue.push(n); + queue.push(...list); return res; } @@ -91,15 +90,14 @@ module.exports = function (text_autospace_filter) { while (node = stack.pop()) { // Push child nodes in reverse order if (list = treeAdapter.getChildNodes(node)) - for (let i = list.length - 1; i >= 0; i--) - stack.push(list[i]); + stack.push(...list.slice().reverse()); // If is text node and not empty if (treeAdapter.isTextNode(node) && !treeAdapter.isEmptyTextNode(node)) { // res always contains at most 1 node if (tmp = res.pop()) crossMatch(tmp, node); - // match inner text and add store the node + // match inner text and store the node node = selfMatch(node); if (treeAdapter.isTextNode(node) && !treeAdapter.isEmptyTextNode(node)) res.push(node); @@ -122,20 +120,21 @@ module.exports = function (text_autospace_filter) { */ function selfMatch(node) { let text = treeAdapter.getTextNodeContent(node); - let matched = false; - patterns.forEach(reg => { - if (text.search(reg) < 0) - return; - matched = true; - text = text.replace(reg, '$1<' + tag_name + '>$2'); - }) + const matched = patterns + .map((reg) => { + const bingo = (text.search(reg) != -1); + if (bingo) + text = text.replace(reg, '$1<' + tag_name + '>$2'); + return bingo; + }) + .reduce((sum, v) => sum || v); if (matched) { const parent = treeAdapter.getParentNode(node); const num = treeAdapter.getNodeIndex(node); // Generate new nodes - let nodeList = treeAdapter.getChildNodes(parse5.parseFragment(text)); + const nodeList = treeAdapter.getChildNodes(parse5.parseFragment(text)); // Insert generated nodes nodeList.forEach(n => { treeAdapter.insertBefore(parent, n, node) }); // Detach original node @@ -158,14 +157,9 @@ module.exports = function (text_autospace_filter) { function crossMatch(node, next) { const pre_text = treeAdapter.getTextNodeContent(node), suf_text = treeAdapter.getTextNodeContent(next); - let matched = false; - - patterns.forEach(reg => { - if ((pre_text + suf_text).search(reg) < 0) - return; - matched = true; - }) + const matched = (-1 != patterns + .findIndex(reg => (pre_text + suf_text).search(reg))) if (!matched) return;