max.js (3089B)
1 import { deepForEach, reduce, containsCollections } from '../../utils/collection.js'; 2 import { factory } from '../../utils/factory.js'; 3 import { improveErrorMessage } from './utils/improveErrorMessage.js'; 4 var name = 'max'; 5 var dependencies = ['typed', 'config', 'numeric', 'larger']; 6 export var createMax = /* #__PURE__ */factory(name, dependencies, _ref => { 7 var { 8 typed, 9 config, 10 numeric, 11 larger 12 } = _ref; 13 14 /** 15 * Compute the maximum value of a matrix or a list with values. 16 * In case of a multi dimensional array, the maximum of the flattened array 17 * will be calculated. When `dim` is provided, the maximum over the selected 18 * dimension will be calculated. Parameter `dim` is zero-based. 19 * 20 * Syntax: 21 * 22 * math.max(a, b, c, ...) 23 * math.max(A) 24 * math.max(A, dim) 25 * 26 * Examples: 27 * 28 * math.max(2, 1, 4, 3) // returns 4 29 * math.max([2, 1, 4, 3]) // returns 4 30 * 31 * // maximum over a specified dimension (zero-based) 32 * math.max([[2, 5], [4, 3], [1, 7]], 0) // returns [4, 7] 33 * math.max([[2, 5], [4, 3]], [1, 7], 1) // returns [5, 4, 7] 34 * 35 * math.max(2.7, 7.1, -4.5, 2.0, 4.1) // returns 7.1 36 * math.min(2.7, 7.1, -4.5, 2.0, 4.1) // returns -4.5 37 * 38 * See also: 39 * 40 * mean, median, min, prod, std, sum, variance 41 * 42 * @param {... *} args A single matrix or or multiple scalar values 43 * @return {*} The maximum value 44 */ 45 return typed(name, { 46 // max([a, b, c, d, ...]) 47 'Array | Matrix': _max, 48 // max([a, b, c, d, ...], dim) 49 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) { 50 return reduce(array, dim.valueOf(), _largest); 51 }, 52 // max(a, b, c, d, ...) 53 '...': function _(args) { 54 if (containsCollections(args)) { 55 throw new TypeError('Scalar values expected in function max'); 56 } 57 58 return _max(args); 59 } 60 }); 61 /** 62 * Return the largest of two values 63 * @param {*} x 64 * @param {*} y 65 * @returns {*} Returns x when x is largest, or y when y is largest 66 * @private 67 */ 68 69 function _largest(x, y) { 70 try { 71 return larger(x, y) ? x : y; 72 } catch (err) { 73 throw improveErrorMessage(err, 'max', y); 74 } 75 } 76 /** 77 * Recursively calculate the maximum value in an n-dimensional array 78 * @param {Array} array 79 * @return {number} max 80 * @private 81 */ 82 83 84 function _max(array) { 85 var res; 86 deepForEach(array, function (value) { 87 try { 88 if (isNaN(value) && typeof value === 'number') { 89 res = NaN; 90 } else if (res === undefined || larger(value, res)) { 91 res = value; 92 } 93 } catch (err) { 94 throw improveErrorMessage(err, 'max', value); 95 } 96 }); 97 98 if (res === undefined) { 99 throw new Error('Cannot calculate max of an empty array'); 100 } // make sure returning numeric value: parse a string into a numeric value 101 102 103 if (typeof res === 'string') { 104 res = numeric(res, config.number); 105 } 106 107 return res; 108 } 109 });