map_function.js (1921B)
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 // MODULES // 22 23 var isFunction = require( '@stdlib/assert/is-function' ); 24 var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; 25 26 27 // MAIN // 28 29 /** 30 * Invokes a function `n` times and returns an array of accumulated function return values. 31 * 32 * @param {Function} fcn - function to invoke 33 * @param {NonNegativeInteger} n - number of function invocations 34 * @param {*} [thisArg] - execution context 35 * @throws {TypeError} first argument must be a function 36 * @throws {TypeError} second argument must be a nonnegative integer 37 * @returns {Array} accumulated results 38 * 39 * @example 40 * function fcn( i ) { 41 * return i; 42 * } 43 * 44 * var arr = mapFun( fcn, 5 ); 45 * // returns [ 0, 1, 2, 3, 4 ] 46 */ 47 function mapFun( fcn, n, thisArg ) { 48 var out; 49 var i; 50 if ( !isFunction( fcn ) ) { 51 throw new TypeError( 'invalid argument. First argument must be a function. Value: `'+fcn+'`.' ); 52 } 53 if ( !isNonNegativeInteger( n ) ) { 54 throw new TypeError( 'invalid argument. Second argument must be a nonnegative integer. Value: `'+n+'`.' ); 55 } 56 // Note: we explicitly do not preallocate in order to ensure "fast" elements for large output arrays. 57 out = []; 58 for ( i = 0; i < n; i++ ) { 59 out.push( fcn.call( thisArg, i ) ); 60 } 61 return out; 62 } 63 64 65 // EXPORTS // 66 67 module.exports = mapFun;