setSize.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. * @return {number} The number of elements of the (multi)set
  30. */
  31. return typed(name, {
  32. 'Array | Matrix': function ArrayMatrix(a) {
  33. return Array.isArray(a) ? flatten(a).length : flatten(a.toArray()).length;
  34. },
  35. 'Array | Matrix, boolean': function ArrayMatrixBoolean(a, unique) {
  36. if (unique === false || a.length === 0) {
  37. return Array.isArray(a) ? flatten(a).length : flatten(a.toArray()).length;
  38. } else {
  39. var b = flatten(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
  40. var count = 1;
  41. for (var i = 1; i < b.length; i++) {
  42. if (compareNatural(b[i], b[i - 1]) !== 0) {
  43. count++;
  44. }
  45. }
  46. return count;
  47. }
  48. }
  49. });
  50. });