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