mode.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { flatten } from '../../utils/array.js';
  2. import { factory } from '../../utils/factory.js';
  3. var name = 'mode';
  4. var dependencies = ['typed', 'isNaN', 'isNumeric'];
  5. export var createMode = /* #__PURE__ */factory(name, dependencies, _ref => {
  6. var {
  7. typed,
  8. isNaN,
  9. isNumeric
  10. } = _ref;
  11. /**
  12. * Computes the mode of a set of numbers or a list with values(numbers or characters).
  13. * If there are multiple modes, it returns a list of those values.
  14. *
  15. * Syntax:
  16. *
  17. * math.mode(a, b, c, ...)
  18. * math.mode(A)
  19. *
  20. * Examples:
  21. *
  22. * math.mode(2, 1, 4, 3, 1) // returns [1]
  23. * math.mode([1, 2.7, 3.2, 4, 2.7]) // returns [2.7]
  24. * math.mode(1, 4, 6, 1, 6) // returns [1, 6]
  25. * math.mode('a','a','b','c') // returns ["a"]
  26. * math.mode(1, 1.5, 'abc') // returns [1, 1.5, "abc"]
  27. *
  28. * See also:
  29. *
  30. * median,
  31. * mean
  32. *
  33. * @param {... *} args A single matrix
  34. * @return {*} The mode of all values
  35. */
  36. return typed(name, {
  37. 'Array | Matrix': _mode,
  38. '...': function _(args) {
  39. return _mode(args);
  40. }
  41. });
  42. /**
  43. * Calculates the mode in an 1-dimensional array
  44. * @param {Array} values
  45. * @return {Array} mode
  46. * @private
  47. */
  48. function _mode(values) {
  49. values = flatten(values.valueOf());
  50. var num = values.length;
  51. if (num === 0) {
  52. throw new Error('Cannot calculate mode of an empty array');
  53. }
  54. var count = {};
  55. var mode = [];
  56. var max = 0;
  57. for (var i = 0; i < values.length; i++) {
  58. var value = values[i];
  59. if (isNumeric(value) && isNaN(value)) {
  60. throw new Error('Cannot calculate mode of an array containing NaN values');
  61. }
  62. if (!(value in count)) {
  63. count[value] = 0;
  64. }
  65. count[value]++;
  66. if (count[value] === max) {
  67. mode.push(value);
  68. } else if (count[value] > max) {
  69. max = count[value];
  70. mode = [value];
  71. }
  72. }
  73. return mode;
  74. }
  75. });