forEach.js 2.0 KB

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