UNPKG

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