Skip to content

fix(set): setUnion returns wrong element order when sets overlap#3675

Open
JSap0914 wants to merge 1 commit into
josdejong:developfrom
JSap0914:fix/issue-195
Open

fix(set): setUnion returns wrong element order when sets overlap#3675
JSap0914 wants to merge 1 commit into
josdejong:developfrom
JSap0914:fix/issue-195

Conversation

@JSap0914

Copy link
Copy Markdown

Problem

math.setUnion() produces incorrect output whenever the two input sets share elements — the intersection is placed at the end instead of its sorted position.

math.setUnion([1, 2, 3, 4], [3, 4, 5, 6])
// before: [1, 2, 5, 6, 3, 4]  ← wrong (intersection at end)
// after:  [1, 2, 3, 4, 5, 6]  ← correct (matches JSDoc example)

Root Cause

The previous implementation:

return concat(setSymDifference(b1, b2), setIntersect(b1, b2))

setSymDifference returns [a-only, b-only], so the result is [a-only, b-only, a∩b] — the shared elements land last.

Fix

Replace with three explicit pieces that are each sorted by their respective helpers:

return concat(concat(setDifference(b1, b2), setIntersect(b1, b2)), setDifference(b2, b1))

This gives the correct sorted union: a-only ++ common ++ b-only.

Changes

  • src/function/set/setUnion.js: swap setSymDifference dependency for setDifference; fix the formula.
  • test/unit-tests/function/set/setUnion.test.js: add overlapping-set assertions (were RED); correct the multiset expected value (was documenting wrong output).

Closes #3674

setUnion([1,2,3,4],[3,4,5,6]) returned [1,2,5,6,3,4] instead of the
documented [1,2,3,4,5,6]. The implementation used
  concat(setSymDifference, setIntersect)
which places the intersection at the end. The correct formula is
  concat(setDifference(a,b), setIntersect(a,b), setDifference(b,a))
so that elements unique to a come first (sorted), then the common
elements (sorted), then elements unique to b (sorted).

Fixes #ISSUE
Copilot AI review requested due to automatic review settings June 30, 2026 04:08

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

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.

bug: setUnion returns wrong element order when sets overlap (intersection placed at end)

2 participants