josdejong / josdejong/mathjs

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

Open Beginner friendly
#3,674 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
15.1k
Forks
1.3k
PR merge metrics
No merged PRs in 30d

Description

## Bug Description

`math.setUnion()` produces incorrect results whenever the two input sets share any elements. The intersection is placed at the **end** of the output rather than in its correct sorted position.

## Reproduction

```js
math.setUnion([1, 2, 3, 4], [3, 4, 5, 6])
// actual: [1, 2, 5, 6, 3, 4]
// expected: [1, 2, 3, 4, 5, 6] ← as documented in the JSDoc

math.setUnion([1, 2], [2, 3])
// actual: [1, 3, 2]
// expected: [1, 2, 3]
```

The JSDoc example explicitly documents `setUnion([1, 2, 3, 4], [3, 4, 5, 6])` → `[1, 2, 3, 4, 5, 6]`.

## Root Cause

The implementation uses:

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

`setSymDifference` returns `[a-only elements, b-only elements]`, so the result is
`[a-only, b-only, a∩b]` — the intersection lands at the end instead of between the two halves.

## Expected Behaviour

Union should return the sorted result: **a-only elements** ++ **common elements** ++ **b-only elements**, i.e.:

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

## Environment

- mathjs version: develop branch

Contributor guide

Open the contributing guide

Research direction

Start at the math.setUnion implementation and compare its current concatenation order with the JSDoc example and the two reproductions in the issue. Verify that overlapping inputs produce a sorted union with exclusive elements before, between, and after the common elements.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
backend-api-design
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Quiet
Clarity
Clearly specified
Newbie friendliness
78/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.