Skip to content

Commit

Permalink
refactor: Reduce use of let instead of const
Browse files Browse the repository at this point in the history
Signed-off-by: Cerallin <cerallin@cerallin.top>
  • Loading branch information
Cerallin committed Jan 19, 2023
1 parent 962ca37 commit 8ec5ccf
Showing 1 changed file with 14 additions and 20 deletions.
34 changes: 14 additions & 20 deletions lib/filter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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);
Expand All @@ -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 + '></' + tag_name + '>$2');
})
const matched = patterns
.map((reg) => {
const bingo = (text.search(reg) != -1);
if (bingo)
text = text.replace(reg, '$1<' + tag_name + '></' + 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
Expand All @@ -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;

Expand Down

0 comments on commit 8ec5ccf

Please sign in to comment.