Skip to content

Commit 857776b

Browse files
authored
Merge pull request #42 from ewdlop/ewdlop-patch-35-Create-mergeNodes.js
Create mergeNodes.js
2 parents 003b341 + 8826c58 commit 857776b

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Javascript/mergeNodes.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
function* mergeNodes(left, right) {
2+
if (!left && !right) return;
3+
if (!left) { yield right; return; }
4+
if (!right) { yield left; return; }
5+
6+
if (left.nodeName !== right.nodeName) {
7+
yield left; yield right; return;
8+
}
9+
10+
const merged = left.cloneNode(false); // 只複製節點本身
11+
Array.from(right.attributes).forEach(attr =>
12+
merged.setAttribute(attr.name, attr.value)); // 屬性覆蓋
13+
14+
merged.textContent = (left.textContent || '') +
15+
(right.textContent || '');
16+
17+
const lChildren = left.childNodes;
18+
const rChildren = right.childNodes;
19+
const len = Math.max(lChildren.length, rChildren.length);
20+
21+
for (let i = 0; i < len; ++i) {
22+
for (const sub of mergeNodes(lChildren[i], rChildren[i])) {
23+
merged.appendChild(sub);
24+
}
25+
}
26+
yield merged;
27+
}

0 commit comments

Comments
 (0)