UNPKG

2.66 kBJavaScriptView Raw
1'use strict';
2
3var flatten = require('../../utils/array').flatten;
4var identify = require('../../utils/array').identify;
5var generalize = require('../../utils/array').generalize;
6
7function factory(type, config, load, typed) {
8 var MatrixIndex = load(require('../../type/matrix/MatrixIndex'));
9 var DenseMatrix = load(require('../../type/matrix/DenseMatrix'));
10 var size = load(require('../matrix/size'));
11 var subset = load(require('../matrix/subset'));
12 var 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 var setDifference = typed('setDifference', {
36 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
37 var result = void 0;
38 if (subset(size(a1), new MatrixIndex(0)) === 0) {
39 // empty-anything=empty
40 result = [];
41 } else if (subset(size(a2), new MatrixIndex(0)) === 0) {
42 // anything-empty=anything
43 return flatten(a1.toArray());
44 } else {
45 var b1 = identify(flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural));
46 var b2 = identify(flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural));
47 result = [];
48 var inb2 = void 0;
49 for (var i = 0; i < b1.length; i++) {
50 inb2 = false;
51 for (var j = 0; j < b2.length; j++) {
52 if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) {
53 // the identifier is always a decimal int
54 inb2 = true;
55 break;
56 }
57 }
58 if (!inb2) {
59 result.push(b1[i]);
60 }
61 }
62 }
63 // return an array, if both inputs were arrays
64 if (Array.isArray(a1) && Array.isArray(a2)) {
65 return generalize(result);
66 }
67 // return a matrix otherwise
68 return new DenseMatrix(generalize(result));
69 }
70 });
71
72 return setDifference;
73}
74
75exports.name = 'setDifference';
76exports.factory = factory;
\No newline at end of file