gen_fcn.js (2193B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 /** 22 * Returns a function to flatten an array containing elements all having the same dimensions. 23 * 24 * @private 25 * @param {PositiveIntegerArray} dims - dimensions 26 * @returns {Function} flatten function 27 */ 28 function genFcn( dims ) { 29 var len; 30 var n; 31 var f; 32 var i; 33 34 // Code generation. Start with the function definition: 35 f = 'return function flattenArray(x){'; 36 37 // Create the function body... 38 len = dims.length; 39 n = len - 1; 40 41 // Create the variables... 42 f += 'var o=[];var '; 43 for ( i = 0; i < len; i++ ) { 44 f += 'i' + i; 45 if ( i < n ) { 46 f += ','; 47 } else { 48 f += ';'; 49 } 50 } 51 // Create the nested for loops... 52 for ( i = 0; i < len; i++ ) { 53 f += 'for(i' + i + '=0;i' + i + '<' + dims[ i ] + ';i' + i + '++){'; 54 } 55 // Create the code which accesses the nested array values and pushes them onto the flattened array. 56 f += 'o.push(x'; 57 for ( i = 0; i < len; i++ ) { 58 f += '[i' + i + ']'; 59 } 60 f += ');'; 61 62 // Closing braces... 63 for ( i = 0; i < len; i++ ) { 64 f += '}'; 65 } 66 f += 'return o;'; 67 68 // Close the function: 69 f += '}'; 70 71 // Add a source directive for debugging: 72 f += '//# sourceURL=flatten_array.gen_fcn.js'; 73 74 // Create the function in the global scope: 75 return ( new Function( f ) )(); // eslint-disable-line no-new-func 76 77 /* 78 * e.g., 79 * 80 * function flattenArray( x ) { 81 * var o = []; 82 * var i0, i1; 83 * for ( i0 = 0; i0 < 2; i0++ ) { 84 * for ( i1 = 0; i1 < 2; i1++ ) { 85 * o.push( x[i0][i1] ); 86 * } 87 * } 88 * return o; 89 * } 90 */ 91 } 92 93 94 // EXPORTS // 95 96 module.exports = genFcn;