UNPKG

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