map.transform.js (2795B)
1 "use strict"; 2 3 Object.defineProperty(exports, "__esModule", { 4 value: true 5 }); 6 exports.createMapTransform = void 0; 7 8 var _is = require("../../utils/is.js"); 9 10 var _function = require("../../utils/function.js"); 11 12 var _array = require("../../utils/array.js"); 13 14 var _factory = require("../../utils/factory.js"); 15 16 var _compileInlineExpression = require("./utils/compileInlineExpression.js"); 17 18 var name = 'map'; 19 var dependencies = ['typed']; 20 var createMapTransform = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) { 21 var typed = _ref.typed; 22 23 /** 24 * Attach a transform function to math.map 25 * Adds a property transform containing the transform function. 26 * 27 * This transform creates a one-based index instead of a zero-based index 28 */ 29 function mapTransform(args, math, scope) { 30 var x, callback; 31 32 if (args[0]) { 33 x = args[0].compile().evaluate(scope); 34 } 35 36 if (args[1]) { 37 if ((0, _is.isSymbolNode)(args[1]) || (0, _is.isFunctionAssignmentNode)(args[1])) { 38 // a function pointer, like filter([3, -2, 5], myTestFunction) 39 callback = args[1].compile().evaluate(scope); 40 } else { 41 // an expression like filter([3, -2, 5], x > 0) 42 callback = (0, _compileInlineExpression.compileInlineExpression)(args[1], math, scope); 43 } 44 } 45 46 return map(x, callback); 47 } 48 49 mapTransform.rawArgs = true; // one-based version of map function 50 51 var map = typed('map', { 52 'Array, function': function ArrayFunction(x, callback) { 53 return _map(x, callback, x); 54 }, 55 'Matrix, function': function MatrixFunction(x, callback) { 56 return x.create(_map(x.valueOf(), callback, x)); 57 } 58 }); 59 return mapTransform; 60 }, { 61 isTransformFunction: true 62 }); 63 /** 64 * Map for a multi dimensional array. One-based indexes 65 * @param {Array} array 66 * @param {function} callback 67 * @param {Array} orig 68 * @return {Array} 69 * @private 70 */ 71 72 exports.createMapTransform = createMapTransform; 73 74 function _map(array, callback, orig) { 75 // figure out what number of arguments the callback function expects 76 var argsCount = (0, _function.maxArgumentCount)(callback); 77 78 function recurse(value, index) { 79 if (Array.isArray(value)) { 80 return (0, _array.map)(value, function (child, i) { 81 // we create a copy of the index array and append the new index value 82 return recurse(child, index.concat(i + 1)); // one based index, hence i + 1 83 }); 84 } else { 85 // invoke the (typed) callback function with the right number of arguments 86 if (argsCount === 1) { 87 return callback(value); 88 } else if (argsCount === 2) { 89 return callback(value, index); 90 } else { 91 // 3 or -1 92 return callback(value, index, orig); 93 } 94 } 95 } 96 97 return recurse(array, []); 98 }