Skip to content

Create mergeNodes.js #42

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

Merged
merged 1 commit into from
Apr 28, 2025
Merged
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
27 changes: 27 additions & 0 deletions Javascript/mergeNodes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
function* mergeNodes(left, right) {
if (!left && !right) return;
if (!left) { yield right; return; }
if (!right) { yield left; return; }

if (left.nodeName !== right.nodeName) {
yield left; yield right; return;
}

const merged = left.cloneNode(false); // 只複製節點本身
Array.from(right.attributes).forEach(attr =>
merged.setAttribute(attr.name, attr.value)); // 屬性覆蓋

merged.textContent = (left.textContent || '') +
(right.textContent || '');

const lChildren = left.childNodes;
const rChildren = right.childNodes;
const len = Math.max(lChildren.length, rChildren.length);

for (let i = 0; i < len; ++i) {
for (const sub of mergeNodes(lChildren[i], rChildren[i])) {
merged.appendChild(sub);
}
}
yield merged;
}