UNPKG

2.31 kBJavaScriptView Raw
1import { flatten, generalize, identify } from '../../utils/array'
2import { factory } from '../../utils/factory'
3
4const name = 'setDifference'
5const dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix']
6
7export const createSetDifference = /* #__PURE__ */ factory(name, dependencies, ({ typed, size, subset, compareNatural, Index, DenseMatrix }) => {
8 /**
9 * Create the difference of two (multi)sets: every element of set1, that is not the element of set2.
10 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
11 *
12 * Syntax:
13 *
14 * math.setDifference(set1, set2)
15 *
16 * Examples:
17 *
18 * math.setDifference([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2]
19 * math.setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2]
20 *
21 * See also:
22 *
23 * setUnion, setIntersect, setSymDifference
24 *
25 * @param {Array | Matrix} a1 A (multi)set
26 * @param {Array | Matrix} a2 A (multi)set
27 * @return {Array | Matrix} The difference of two (multi)sets
28 */
29 return typed(name, {
30 'Array | Matrix, Array | Matrix': function (a1, a2) {
31 let result
32 if (subset(size(a1), new Index(0)) === 0) { // empty-anything=empty
33 result = []
34 } else if (subset(size(a2), new Index(0)) === 0) { // anything-empty=anything
35 return flatten(a1.toArray())
36 } else {
37 const b1 = identify(flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural))
38 const b2 = identify(flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural))
39 result = []
40 let inb2
41 for (let i = 0; i < b1.length; i++) {
42 inb2 = false
43 for (let j = 0; j < b2.length; j++) {
44 if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) { // the identifier is always a decimal int
45 inb2 = true
46 break
47 }
48 }
49 if (!inb2) {
50 result.push(b1[i])
51 }
52 }
53 }
54 // return an array, if both inputs were arrays
55 if (Array.isArray(a1) && Array.isArray(a2)) {
56 return generalize(result)
57 }
58 // return a matrix otherwise
59 return new DenseMatrix(generalize(result))
60 }
61 })
62})