UNPKG

2.78 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.createMapTransform = 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 = 'map';
19var dependencies = ['typed'];
20var createMapTransform =
21/* #__PURE__ */
22(0, _factory.factory)(name, dependencies, function (_ref) {
23 var typed = _ref.typed;
24
25 /**
26 * Attach a transform function to math.map
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 mapTransform(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 filter([3, -2, 5], myTestFunction)
41 callback = args[1].compile().evaluate(scope);
42 } else {
43 // an expression like filter([3, -2, 5], x > 0)
44 callback = (0, _compileInlineExpression.compileInlineExpression)(args[1], math, scope);
45 }
46 }
47
48 return map(x, callback);
49 }
50
51 mapTransform.rawArgs = true; // one-based version of map function
52
53 var map = typed('map', {
54 'Array, function': function ArrayFunction(x, callback) {
55 return _map(x, callback, x);
56 },
57 'Matrix, function': function MatrixFunction(x, callback) {
58 return x.create(_map(x.valueOf(), callback, x));
59 }
60 });
61 return mapTransform;
62}, {
63 isTransformFunction: true
64});
65/**
66 * Map for a multi dimensional array. One-based indexes
67 * @param {Array} array
68 * @param {function} callback
69 * @param {Array} orig
70 * @return {Array}
71 * @private
72 */
73
74exports.createMapTransform = createMapTransform;
75
76function _map(array, callback, orig) {
77 // figure out what number of arguments the callback function expects
78 var argsCount = (0, _function.maxArgumentCount)(callback);
79
80 function recurse(value, index) {
81 if (Array.isArray(value)) {
82 return (0, _array.map)(value, function (child, i) {
83 // we create a copy of the index array and append the new index value
84 return recurse(child, index.concat(i + 1)); // one based index, hence i + 1
85 });
86 } else {
87 // invoke the (typed) callback function with the right number of arguments
88 if (argsCount === 1) {
89 return callback(value);
90 } else if (argsCount === 2) {
91 return callback(value, index);
92 } else {
93 // 3 or -1
94 return callback(value, index, orig);
95 }
96 }
97 }
98
99 return recurse(array, []);
100}
\No newline at end of file