diff --git a/src/function/set/setUnion.js b/src/function/set/setUnion.js index ce53bea081..77355b49e1 100644 --- a/src/function/set/setUnion.js +++ b/src/function/set/setUnion.js @@ -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. @@ -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)) } }) }) diff --git a/test/unit-tests/function/set/setUnion.test.js b/test/unit-tests/function/set/setUnion.test.js index b8bf6f5c68..b51a7bf5fb 100644 --- a/test/unit-tests/function/set/setUnion.test.js +++ b/test/unit-tests/function/set/setUnion.test.js @@ -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 () {