prod.js 2.5 KB

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