UNPKG

1.7 kBJavaScriptView Raw
1'use strict'
2
3const flatten = require('../../utils/array').flatten
4
5function factory (type, config, load, typed) {
6 const MatrixIndex = load(require('../../type/matrix/MatrixIndex'))
7 const DenseMatrix = load(require('../../type/matrix/DenseMatrix'))
8 const size = load(require('../matrix/size'))
9 const subset = load(require('../matrix/subset'))
10 const compareNatural = load(require('../relational/compareNatural'))
11
12 /**
13 * Collect the distinct elements of a multiset.
14 * A multi-dimension array will be converted to a single-dimension array before the operation.
15 *
16 * Syntax:
17 *
18 * math.setDistinct(set)
19 *
20 * Examples:
21 *
22 * math.setDistinct([1, 1, 1, 2, 2, 3]) // returns [1, 2, 3]
23 *
24 * See also:
25 *
26 * setMultiplicity
27 *
28 * @param {Array | Matrix} a A multiset
29 * @return {Array | Matrix} A set containing the distinc elements of the multiset
30 */
31 const setDistinct = typed('setDistinct', {
32 'Array | Matrix': function (a) {
33 let result
34 if (subset(size(a), new MatrixIndex(0)) === 0) { // if empty, return empty
35 result = []
36 } else {
37 const b = flatten(Array.isArray(a) ? a : a.toArray()).sort(compareNatural)
38 result = []
39 result.push(b[0])
40 for (let i = 1; i < b.length; i++) {
41 if (compareNatural(b[i], b[i - 1]) !== 0) {
42 result.push(b[i])
43 }
44 }
45 }
46 // return an array, if the input was an array
47 if (Array.isArray(a)) {
48 return result
49 }
50 // return a matrix otherwise
51 return new DenseMatrix(result)
52 }
53 })
54
55 return setDistinct
56}
57
58exports.name = 'setDistinct'
59exports.factory = factory