UNPKG

1.73 kBJavaScriptView Raw
1'use strict';
2
3var flatten = require('../../utils/array').flatten;
4
5function factory(type, config, load, typed) {
6 var MatrixIndex = load(require('../../type/matrix/MatrixIndex'));
7 var DenseMatrix = load(require('../../type/matrix/DenseMatrix'));
8 var size = load(require('../matrix/size'));
9 var subset = load(require('../matrix/subset'));
10 var 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 var setDistinct = typed('setDistinct', {
32 'Array | Matrix': function ArrayMatrix(a) {
33 var result = void 0;
34 if (subset(size(a), new MatrixIndex(0)) === 0) {
35 // if empty, return empty
36 result = [];
37 } else {
38 var b = flatten(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
39 result = [];
40 result.push(b[0]);
41 for (var i = 1; i < b.length; i++) {
42 if (compareNatural(b[i], b[i - 1]) !== 0) {
43 result.push(b[i]);
44 }
45 }
46 }
47 // return an array, if the input was an array
48 if (Array.isArray(a)) {
49 return result;
50 }
51 // return a matrix otherwise
52 return new DenseMatrix(result);
53 }
54 });
55
56 return setDistinct;
57}
58
59exports.name = 'setDistinct';
60exports.factory = factory;
\No newline at end of file