Skip to content
Open
Show file tree
Hide file tree
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
8 changes: 5 additions & 3 deletions src/function/set/setUnion.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { flatten } from '../../utils/array.js'
import { factory } from '../../utils/factory.js'

const name = 'setUnion'
const dependencies = ['typed', 'size', 'concat', 'subset', 'setIntersect', 'setSymDifference', 'Index']
const dependencies = ['typed', 'size', 'concat', 'subset', 'setDifference', 'setIntersect', 'Index']

export const createSetUnion = /* #__PURE__ */ factory(name, dependencies, ({ typed, size, concat, subset, setIntersect, setSymDifference, Index }) => {
export const createSetUnion = /* #__PURE__ */ factory(name, dependencies, ({ typed, size, concat, subset, setDifference, setIntersect, Index }) => {
/**
* Create the union of two (multi)sets.
* Multi-dimension arrays will be converted to single-dimension arrays before the operation.
Expand Down Expand Up @@ -35,7 +35,9 @@ export const createSetUnion = /* #__PURE__ */ factory(name, dependencies, ({ typ
}
const b1 = flatten(a1)
const b2 = flatten(a2)
return concat(setSymDifference(b1, b2), setIntersect(b1, b2))
// union = elements only in a1 + elements in both + elements only in a2
// (all three sub-results are sorted by setDifference/setIntersect internally)
return concat(concat(setDifference(b1, b2), setIntersect(b1, b2)), setDifference(b2, b1))
}
})
})
5 changes: 4 additions & 1 deletion test/unit-tests/function/set/setUnion.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@ describe('setUnion', function () {
assert.deepStrictEqual(math.setUnion(['a', 'b'], ['c', 'd']), ['a', 'b', 'c', 'd'])
assert.deepStrictEqual(math.setUnion([], [3, 4]), [3, 4])
assert.deepStrictEqual(math.setUnion([], []), [])
// sets with overlapping elements must include all unique elements in sorted order
assert.deepStrictEqual(math.setUnion([1, 2, 3, 4], [3, 4, 5, 6]), [1, 2, 3, 4, 5, 6])
assert.deepStrictEqual(math.setUnion([1, 2], [2, 3]), [1, 2, 3])
})

it('should return the union of two multisets', function () {
assert.deepStrictEqual(math.setUnion([1, 1, 2, 3, 4, 4], [1, 2, 3, 4, 4, 4]), [1, 4, 1, 2, 3, 4, 4])
assert.deepStrictEqual(math.setUnion([1, 1, 2, 3, 4, 4], [1, 2, 3, 4, 4, 4]), [1, 1, 2, 3, 4, 4, 4])
})

it('should return the same type of output as the inputs', function () {
Expand Down