map.transform.js (2578B)
1 import { isFunctionAssignmentNode, isSymbolNode } from '../../utils/is.js'; 2 import { maxArgumentCount } from '../../utils/function.js'; 3 import { map } from '../../utils/array.js'; 4 import { factory } from '../../utils/factory.js'; 5 import { compileInlineExpression } from './utils/compileInlineExpression.js'; 6 var name = 'map'; 7 var dependencies = ['typed']; 8 export var createMapTransform = /* #__PURE__ */factory(name, dependencies, _ref => { 9 var { 10 typed 11 } = _ref; 12 13 /** 14 * Attach a transform function to math.map 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 mapTransform(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 filter([3, -2, 5], myTestFunction) 29 callback = args[1].compile().evaluate(scope); 30 } else { 31 // an expression like filter([3, -2, 5], x > 0) 32 callback = compileInlineExpression(args[1], math, scope); 33 } 34 } 35 36 return map(x, callback); 37 } 38 39 mapTransform.rawArgs = true; // one-based version of map function 40 41 var map = typed('map', { 42 'Array, function': function ArrayFunction(x, callback) { 43 return _map(x, callback, x); 44 }, 45 'Matrix, function': function MatrixFunction(x, callback) { 46 return x.create(_map(x.valueOf(), callback, x)); 47 } 48 }); 49 return mapTransform; 50 }, { 51 isTransformFunction: true 52 }); 53 /** 54 * Map for a multi dimensional array. One-based indexes 55 * @param {Array} array 56 * @param {function} callback 57 * @param {Array} orig 58 * @return {Array} 59 * @private 60 */ 61 62 function _map(array, callback, orig) { 63 // figure out what number of arguments the callback function expects 64 var argsCount = maxArgumentCount(callback); 65 66 function recurse(value, index) { 67 if (Array.isArray(value)) { 68 return map(value, function (child, i) { 69 // we create a copy of the index array and append the new index value 70 return recurse(child, index.concat(i + 1)); // one based index, hence i + 1 71 }); 72 } else { 73 // invoke the (typed) callback function with the right number of arguments 74 if (argsCount === 1) { 75 return callback(value); 76 } else if (argsCount === 2) { 77 return callback(value, index); 78 } else { 79 // 3 or -1 80 return callback(value, index, orig); 81 } 82 } 83 } 84 85 return recurse(array, []); 86 }