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

Create mergeNodes.js #42

merged 1 commit into from
Apr 28, 2025

Conversation

ewdlop
Copy link
Owner

@ewdlop ewdlop commented Apr 28, 2025

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;
}

```javascript
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;
}
```
@ewdlop ewdlop self-assigned this Apr 28, 2025
@ewdlop ewdlop merged commit 857776b into main Apr 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant