setSize.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { flatten } from '../../utils/array.js';
  2. import { factory } from '../../utils/factory.js';
  3. var name = 'setSize';
  4. var dependencies = ['typed', 'compareNatural'];
  5. export var createSetSize = /* #__PURE__ */factory(name, dependencies, _ref => {
  6. var {
  7. typed,
  8. compareNatural
  9. } = _ref;
  10. /**
  11. * Count the number of elements of a (multi)set. When a second parameter is 'true', count only the unique values.
  12. * A multi-dimension array will be converted to a single-dimension array before the operation.
  13. *
  14. * Syntax:
  15. *
  16. * math.setSize(set)
  17. * math.setSize(set, unique)
  18. *
  19. * Examples:
  20. *
  21. * math.setSize([1, 2, 2, 4]) // returns 4
  22. * math.setSize([1, 2, 2, 4], true) // returns 3
  23. *
  24. * See also:
  25. *
  26. * setUnion, setIntersect, setDifference
  27. *
  28. * @param {Array | Matrix} a A multiset
  29. * @param {boolean} [unique] If true, only the unique values are counted. False by default
  30. * @return {number} The number of elements of the (multi)set
  31. */
  32. return typed(name, {
  33. 'Array | Matrix': function ArrayMatrix(a) {
  34. return Array.isArray(a) ? flatten(a).length : flatten(a.toArray()).length;
  35. },
  36. 'Array | Matrix, boolean': function ArrayMatrixBoolean(a, unique) {
  37. if (unique === false || a.length === 0) {
  38. return Array.isArray(a) ? flatten(a).length : flatten(a.toArray()).length;
  39. } else {
  40. var b = flatten(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
  41. var count = 1;
  42. for (var i = 1; i < b.length; i++) {
  43. if (compareNatural(b[i], b[i - 1]) !== 0) {
  44. count++;
  45. }
  46. }
  47. return count;
  48. }
  49. }
  50. });
  51. });