UNPKG

1.48 kBJavaScriptView Raw
1import { flatten } from '../../utils/array'
2import { factory } from '../../utils/factory'
3
4const name = 'setSymDifference'
5const dependencies = ['typed', 'size', 'concat', 'subset', 'setDifference', 'Index']
6
7export const createSetSymDifference = /* #__PURE__ */ factory(name, dependencies, ({ typed, size, concat, subset, setDifference, Index }) => {
8 /**
9 * Create the symmetric difference of two (multi)sets.
10 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
11 *
12 * Syntax:
13 *
14 * math.setSymDifference(set1, set2)
15 *
16 * Examples:
17 *
18 * math.setSymDifference([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2, 5, 6]
19 * math.setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2, 5, 6]
20 *
21 * See also:
22 *
23 * setUnion, setIntersect, setDifference
24 *
25 * @param {Array | Matrix} a1 A (multi)set
26 * @param {Array | Matrix} a2 A (multi)set
27 * @return {Array | Matrix} The symmetric difference 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(setDifference(b1, b2), setDifference(b2, b1))
39 }
40 })
41})