prod.js (2574B)
1 "use strict"; 2 3 Object.defineProperty(exports, "__esModule", { 4 value: true 5 }); 6 exports.createProd = void 0; 7 8 var _collection = require("../../utils/collection.js"); 9 10 var _factory = require("../../utils/factory.js"); 11 12 var _improveErrorMessage = require("./utils/improveErrorMessage.js"); 13 14 var name = 'prod'; 15 var dependencies = ['typed', 'config', 'multiplyScalar', 'numeric']; 16 var createProd = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) { 17 var typed = _ref.typed, 18 config = _ref.config, 19 multiplyScalar = _ref.multiplyScalar, 20 numeric = _ref.numeric; 21 22 /** 23 * Compute the product of a matrix or a list with values. 24 * In case of a (multi dimensional) array or matrix, the sum of all 25 * elements will be calculated. 26 * 27 * Syntax: 28 * 29 * math.prod(a, b, c, ...) 30 * math.prod(A) 31 * 32 * Examples: 33 * 34 * math.multiply(2, 3) // returns 6 35 * math.prod(2, 3) // returns 6 36 * math.prod(2, 3, 4) // returns 24 37 * math.prod([2, 3, 4]) // returns 24 38 * math.prod([[2, 5], [4, 3]]) // returns 120 39 * 40 * See also: 41 * 42 * mean, median, min, max, sum, std, variance 43 * 44 * @param {... *} args A single matrix or or multiple scalar values 45 * @return {*} The product of all values 46 */ 47 return typed(name, { 48 // prod([a, b, c, d, ...]) 49 'Array | Matrix': _prod, 50 // prod([a, b, c, d, ...], dim) 51 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) { 52 // TODO: implement prod(A, dim) 53 throw new Error('prod(A, dim) is not yet supported'); // return reduce(arguments[0], arguments[1], math.prod) 54 }, 55 // prod(a, b, c, d, ...) 56 '...': function _(args) { 57 return _prod(args); 58 } 59 }); 60 /** 61 * Recursively calculate the product of an n-dimensional array 62 * @param {Array} array 63 * @return {number} prod 64 * @private 65 */ 66 67 function _prod(array) { 68 var prod; 69 (0, _collection.deepForEach)(array, function (value) { 70 try { 71 prod = prod === undefined ? value : multiplyScalar(prod, value); 72 } catch (err) { 73 throw (0, _improveErrorMessage.improveErrorMessage)(err, 'prod', value); 74 } 75 }); // make sure returning numeric value: parse a string into a numeric value 76 77 if (typeof prod === 'string') { 78 prod = numeric(prod, config.number); 79 } 80 81 if (prod === undefined) { 82 throw new Error('Cannot calculate prod of an empty array'); 83 } 84 85 return prod; 86 } 87 }); 88 exports.createProd = createProd;