mode.js 2.2 KB

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