sum.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.createSum = 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 = 'sum';
  10. var dependencies = ['typed', 'config', 'add', 'numeric'];
  11. var createSum = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) {
  12. var typed = _ref.typed,
  13. config = _ref.config,
  14. add = _ref.add,
  15. numeric = _ref.numeric;
  16. /**
  17. * Compute the sum 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.sum(a, b, c, ...)
  24. * math.sum(A)
  25. * math.sum(A, dimension)
  26. *
  27. * Examples:
  28. *
  29. * math.sum(2, 1, 4, 3) // returns 10
  30. * math.sum([2, 1, 4, 3]) // returns 10
  31. * math.sum([[2, 5], [4, 3], [1, 7]]) // returns 22
  32. *
  33. * See also:
  34. *
  35. * mean, median, min, max, prod, std, variance, cumsum
  36. *
  37. * @param {... *} args A single matrix or multiple scalar values
  38. * @return {*} The sum of all values
  39. */
  40. return typed(name, {
  41. // sum([a, b, c, d, ...])
  42. 'Array | Matrix': _sum,
  43. // sum([a, b, c, d, ...], dim)
  44. 'Array | Matrix, number | BigNumber': _nsumDim,
  45. // sum(a, b, c, d, ...)
  46. '...': function _(args) {
  47. if ((0, _collection.containsCollections)(args)) {
  48. throw new TypeError('Scalar values expected in function sum');
  49. }
  50. return _sum(args);
  51. }
  52. });
  53. /**
  54. * Recursively calculate the sum of an n-dimensional array
  55. * @param {Array | Matrix} array
  56. * @return {number} sum
  57. * @private
  58. */
  59. function _sum(array) {
  60. var sum;
  61. (0, _collection.deepForEach)(array, function (value) {
  62. try {
  63. sum = sum === undefined ? value : add(sum, value);
  64. } catch (err) {
  65. throw (0, _improveErrorMessage.improveErrorMessage)(err, 'sum', value);
  66. }
  67. });
  68. // make sure returning numeric value: parse a string into a numeric value
  69. if (sum === undefined) {
  70. sum = numeric(0, config.number);
  71. }
  72. if (typeof sum === 'string') {
  73. sum = numeric(sum, config.number);
  74. }
  75. return sum;
  76. }
  77. function _nsumDim(array, dim) {
  78. try {
  79. var sum = (0, _collection.reduce)(array, dim, add);
  80. return sum;
  81. } catch (err) {
  82. throw (0, _improveErrorMessage.improveErrorMessage)(err, 'sum');
  83. }
  84. }
  85. });
  86. exports.createSum = createSum;