UNPKG

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