UNPKG

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