UNPKG

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