UNPKG

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