UNPKG

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