Skip to content

Commit

Permalink
reduce nesting in search function
Browse files Browse the repository at this point in the history
  • Loading branch information
zendive committed Feb 6, 2024
1 parent 8e58fe2 commit ee4b184
Showing 1 changed file with 33 additions and 22 deletions.
55 changes: 33 additions & 22 deletions src/stores/search.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,29 +127,40 @@ function highlightAll(

const containerNodes = <NodeListOf<HTMLElement>>container.childNodes;

if (containerNodes.length) {
const firstChild = containerNodes[0];

if (containerNodes.length === 1 && firstChild.nodeType === Node.TEXT_NODE) {
const text = firstChild.textContent || firstChild.innerText;
const found = UPPERCASE_PATTERN.test(query)
? text.includes(query) // case-sensitive
: text.toLocaleLowerCase().includes(query); // case-insensitive
const isHidden =
container.closest('.jsondiffpatch-unchanged-hidden') &&
container.closest('.jsondiffpatch-unchanged');

if (found && !isHidden) {
container.classList.add('jsdiff-found');
els.push(markRaw(container));
}
} else {
for (let n = 0, N = containerNodes.length; n < N; n++) {
const child = containerNodes[n];
if (!containerNodes.length) {
return;
}

if (child.nodeType === Node.ELEMENT_NODE) {
highlightAll(child, query, els); // recursion
}
const firstChild = containerNodes[0];
const isLeafNode =
containerNodes.length === 1 && firstChild.nodeType === Node.TEXT_NODE;

if (isLeafNode) {
const text = firstChild.textContent || firstChild.innerText;
const hasMatch = UPPERCASE_PATTERN.test(query)
? text.includes(query) // case-sensitive
: text.toLocaleLowerCase().includes(query); // case-insensitive

if (!hasMatch) {
return;
}

const isHidden =
container.closest('.jsondiffpatch-unchanged-hidden') &&
container.closest('.jsondiffpatch-unchanged');

if (isHidden) {
return;
}

container.classList.add('jsdiff-found');
els.push(markRaw(container));
} else {
for (let n = 0, N = containerNodes.length; n < N; n++) {
const child = containerNodes[n];

if (child.nodeType === Node.ELEMENT_NODE) {
highlightAll(child, query, els); // recursion
}
}
}
Expand Down

0 comments on commit ee4b184

Please sign in to comment.