UNPKG

2.35 kBJavaScriptView Raw
1import { isFunctionAssignmentNode, isSymbolNode } from '../../utils/is.js';
2import { maxArgumentCount } from '../../utils/function.js';
3import { forEach } from '../../utils/array.js';
4import { factory } from '../../utils/factory.js';
5import { compileInlineExpression } from './utils/compileInlineExpression.js';
6var name = 'forEach';
7var dependencies = ['typed'];
8export var createForEachTransform = /* #__PURE__ */factory(name, dependencies, _ref => {
9 var {
10 typed
11 } = _ref;
12
13 /**
14 * Attach a transform function to math.forEach
15 * Adds a property transform containing the transform function.
16 *
17 * This transform creates a one-based index instead of a zero-based index
18 */
19 function forEachTransform(args, math, scope) {
20 var x, callback;
21
22 if (args[0]) {
23 x = args[0].compile().evaluate(scope);
24 }
25
26 if (args[1]) {
27 if (isSymbolNode(args[1]) || isFunctionAssignmentNode(args[1])) {
28 // a function pointer, like forEach([3, -2, 5], myTestFunction)
29 callback = args[1].compile().evaluate(scope);
30 } else {
31 // an expression like forEach([3, -2, 5], x > 0 ? callback1(x) : callback2(x) )
32 callback = compileInlineExpression(args[1], math, scope);
33 }
34 }
35
36 return _forEach(x, callback);
37 }
38
39 forEachTransform.rawArgs = true; // one-based version of forEach
40
41 var _forEach = typed('forEach', {
42 'Array | Matrix, function': function ArrayMatrixFunction(array, callback) {
43 // figure out what number of arguments the callback function expects
44 var args = maxArgumentCount(callback);
45
46 var recurse = function recurse(value, index) {
47 if (Array.isArray(value)) {
48 forEach(value, function (child, i) {
49 // we create a copy of the index array and append the new index value
50 recurse(child, index.concat(i + 1)); // one based index, hence i+1
51 });
52 } else {
53 // invoke the callback function with the right number of arguments
54 if (args === 1) {
55 callback(value);
56 } else if (args === 2) {
57 callback(value, index);
58 } else {
59 // 3 or -1
60 callback(value, index, array);
61 }
62 }
63 };
64
65 recurse(array.valueOf(), []); // pass Array
66 }
67 });
68
69 return forEachTransform;
70}, {
71 isTransformFunction: true
72});
\No newline at end of file