UNPKG

1.55 kBJavaScriptView Raw
1'use strict'
2
3const flatten = require('../../utils/array').flatten
4
5function factory (type, config, load, typed) {
6 const compareNatural = load(require('../relational/compareNatural'))
7
8 /**
9 * Count the number of elements of a (multi)set. When a second parameter is 'true', count only the unique values.
10 * A multi-dimension array will be converted to a single-dimension array before the operation.
11 *
12 * Syntax:
13 *
14 * math.setSize(set)
15 * math.setSize(set, unique)
16 *
17 * Examples:
18 *
19 * math.setSize([1, 2, 2, 4]) // returns 4
20 * math.setSize([1, 2, 2, 4], true) // returns 3
21 *
22 * See also:
23 *
24 * setUnion, setIntersect, setDifference
25 *
26 * @param {Array | Matrix} a A multiset
27 * @return {number} The number of elements of the (multi)set
28 */
29 const setSize = typed('setSize', {
30 'Array | Matrix': function (a) {
31 return Array.isArray(a) ? flatten(a).length : flatten(a.toArray()).length
32 },
33 'Array | Matrix, boolean': function (a, unique) {
34 if (unique === false || a.length === 0) {
35 return Array.isArray(a) ? flatten(a).length : flatten(a.toArray()).length
36 } else {
37 const b = flatten(Array.isArray(a) ? a : a.toArray()).sort(compareNatural)
38 let count = 1
39 for (let i = 1; i < b.length; i++) {
40 if (compareNatural(b[i], b[i - 1]) !== 0) {
41 count++
42 }
43 }
44 return count
45 }
46 }
47 })
48
49 return setSize
50}
51
52exports.name = 'setSize'
53exports.factory = factory