1 |
|
2 |
|
3 | const maxArgumentCount = require('../../utils/function').maxArgumentCount
|
4 | const forEach = require('../../utils/array').forEach
|
5 |
|
6 | function factory (type, config, load, typed) {
|
7 | /**
|
8 | * Iterate over all elements of a matrix/array, and executes the given callback function.
|
9 | *
|
10 | * Syntax:
|
11 | *
|
12 | * math.forEach(x, callback)
|
13 | *
|
14 | * Examples:
|
15 | *
|
16 | * math.forEach([1, 2, 3], function(value) {
|
17 | * console.log(value)
|
18 | * })
|
19 | * // outputs 1, 2, 3
|
20 | *
|
21 | * See also:
|
22 | *
|
23 | * filter, map, sort
|
24 | *
|
25 | * @param {Matrix | Array} x The matrix to iterate on.
|
26 | * @param {Function} callback The callback function is invoked with three
|
27 | * parameters: the value of the element, the index
|
28 | * of the element, and the Matrix/array being traversed.
|
29 | */
|
30 | const forEach = typed('forEach', {
|
31 | 'Array, function': _forEach,
|
32 |
|
33 | 'Matrix, function': function (x, callback) {
|
34 | return x.forEach(callback)
|
35 | }
|
36 | })
|
37 |
|
38 | forEach.toTex = undefined // use default template
|
39 |
|
40 | return forEach
|
41 | }
|
42 |
|
43 | /**
|
44 | * forEach for a multi dimensional array
|
45 | * @param {Array} array
|
46 | * @param {Function} callback
|
47 | * @private
|
48 | */
|
49 | function _forEach (array, callback) {
|
50 | // figure out what number of arguments the callback function expects
|
51 | const args = maxArgumentCount(callback)
|
52 |
|
53 | const recurse = function (value, index) {
|
54 | if (Array.isArray(value)) {
|
55 | 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 { // 3 or -1
|
66 | callback(value, index, array)
|
67 | }
|
68 | }
|
69 | }
|
70 | recurse(array, [])
|
71 | }
|
72 |
|
73 | exports.name = 'forEach'
|
74 | exports.factory = factory
|