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