forEach.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.createForEach = void 0;
  6. var _function = require("../../utils/function.js");
  7. var _array = require("../../utils/array.js");
  8. var _factory = require("../../utils/factory.js");
  9. var name = 'forEach';
  10. var dependencies = ['typed'];
  11. var createForEach = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) {
  12. var typed = _ref.typed;
  13. /**
  14. * Iterate over all elements of a matrix/array, and executes the given callback function.
  15. *
  16. * Syntax:
  17. *
  18. * math.forEach(x, callback)
  19. *
  20. * Examples:
  21. *
  22. * math.forEach([1, 2, 3], function(value) {
  23. * console.log(value)
  24. * })
  25. * // outputs 1, 2, 3
  26. *
  27. * See also:
  28. *
  29. * filter, map, sort
  30. *
  31. * @param {Matrix | Array} x The matrix to iterate on.
  32. * @param {Function} callback The callback function is invoked with three
  33. * parameters: the value of the element, the index
  34. * of the element, and the Matrix/array being traversed.
  35. */
  36. return typed(name, {
  37. 'Array, function': _forEach,
  38. 'Matrix, function': function MatrixFunction(x, callback) {
  39. x.forEach(callback);
  40. }
  41. });
  42. });
  43. /**
  44. * forEach for a multi dimensional array
  45. * @param {Array} array
  46. * @param {Function} callback
  47. * @private
  48. */
  49. exports.createForEach = createForEach;
  50. function _forEach(array, callback) {
  51. // figure out what number of arguments the callback function expects
  52. var args = (0, _function.maxArgumentCount)(callback);
  53. var recurse = function recurse(value, index) {
  54. if (Array.isArray(value)) {
  55. (0, _array.forEach)(value, function (child, i) {
  56. // we create a copy of the index array and append the new index value
  57. recurse(child, index.concat(i));
  58. });
  59. } else {
  60. // invoke the callback function with the right number of arguments
  61. if (args === 1) {
  62. callback(value);
  63. } else if (args === 2) {
  64. callback(value, index);
  65. } else {
  66. // 3 or -1
  67. callback(value, index, array);
  68. }
  69. }
  70. };
  71. recurse(array, []);
  72. }