Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement normalize function #166

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/dom/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,32 @@ export class Node extends EventTarget {
oldChild._replaceWith(newChild);
return oldChild;
}
normalize() {
let i = 0;
while (i < this.childNodes.length) {
const currentNode = this.childNodes[i];
if (currentNode.nodeType === NodeType.TEXT_NODE) {
let nextNode = this.childNodes[i + 1];

// Merge adjacent text nodes
while (nextNode && nextNode.nodeType === NodeType.TEXT_NODE) {
if (currentNode.nodeValue) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need this if, adding an empty string would have the same effect

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, noticing that this if will drop the text from non-empty text nodes that follow empty text nodes

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, following the standard algorithm outlined here if any of the first text nodes found before others is empty then it's deleted and then the first non-empty text node will receive your currentNode treatment as you have here

currentNode.nodeValue += nextNode.nodeValue;
}
this.removeChild(nextNode);
nextNode = this.childNodes[i + 1];
}
if (currentNode.nodeValue === "") {
this.removeChild(currentNode);
} else {
i++;
}
} else {
currentNode.normalize();
i++;
}
}
}

insertBefore(newNode: Node, refNode: Node | null): Node {
this._assertNotAncestor(newNode);
Expand Down
Loading