time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

reverse_arguments.js (1781B)


      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 
     25 
     26 // MAIN //
     27 
     28 /**
     29 * Returns a function that invokes a provided function with arguments in reverse order.
     30 *
     31 * @param {Function} fcn - input function
     32 * @param {*} [thisArg] - function context
     33 * @throws {TypeError} first argument must be a function
     34 * @returns {Function} reverse arguments function
     35 *
     36 * @example
     37 * function foo( a, b, c ) {
     38 *     return [ a, b, c ];
     39 * }
     40 *
     41 * var bar = reverseArguments( foo );
     42 *
     43 * var out = bar( 1, 2, 3 );
     44 * // returns [ 3, 2, 1 ]
     45 */
     46 function reverseArguments( fcn, thisArg ) {
     47 	if ( !isFunction( fcn ) ) {
     48 		throw new TypeError( 'invalid argument. First argument must be a function. Value: `'+fcn+'`.' );
     49 	}
     50 	return reversed;
     51 
     52 	/**
     53 	* Invokes a function with arguments in reverse order.
     54 	*
     55 	* @private
     56 	* @param {...*} args - arguments
     57 	* @returns {*} return value
     58 	*/
     59 	function reversed() {
     60 		var args;
     61 		var len;
     62 		var i;
     63 
     64 		len = arguments.length;
     65 		args = new Array( len );
     66 		for ( i = 0; i < len; i++ ) {
     67 			args[ len-1-i ] = arguments[ i ];
     68 		}
     69 		return fcn.apply( thisArg, args );
     70 	}
     71 }
     72 
     73 
     74 // EXPORTS //
     75 
     76 module.exports = reverseArguments;