UNPKG

1.45 kBJavaScriptView Raw
1import { flatten } from '../../utils/array'
2import { factory } from '../../utils/factory'
3
4const name = 'setUnion'
5const dependencies = ['typed', 'size', 'concat', 'subset', 'setIntersect', 'setSymDifference', 'Index']
6
7export const createSetUnion = /* #__PURE__ */ factory(name, dependencies, ({ typed, size, concat, subset, setIntersect, setSymDifference, Index }) => {
8 /**
9 * Create the union of two (multi)sets.
10 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
11 *
12 * Syntax:
13 *
14 * math.setUnion(set1, set2)
15 *
16 * Examples:
17 *
18 * math.setUnion([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2, 3, 4, 5, 6]
19 * math.setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2, 3, 4, 5, 6]
20 *
21 * See also:
22 *
23 * setIntersect, setDifference
24 *
25 * @param {Array | Matrix} a1 A (multi)set
26 * @param {Array | Matrix} a2 A (multi)set
27 * @return {Array | Matrix} The union of two (multi)sets
28 */
29 return typed(name, {
30 'Array | Matrix, Array | Matrix': function (a1, a2) {
31 if (subset(size(a1), new Index(0)) === 0) { // if any of them is empty, return the other one
32 return flatten(a2)
33 } else if (subset(size(a2), new Index(0)) === 0) {
34 return flatten(a1)
35 }
36 const b1 = flatten(a1)
37 const b2 = flatten(a2)
38 return concat(setSymDifference(b1, b2), setIntersect(b1, b2))
39 }
40 })
41})