time-to-botec

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

papply.js (1849B)


      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 of smaller arity by partially applying arguments.
     30 *
     31 * @param {Function} fcn - function to partially apply
     32 * @param {...*} [args] - arguments to partially apply
     33 * @throws {TypeError} first argument must be a function
     34 * @returns {Function} partially applied function
     35 *
     36 * @example
     37 * function add( x, y ) {
     38 *     return x + y;
     39 * }
     40 *
     41 * var add2 = papply( add, 2 );
     42 *
     43 * var sum = add2( 3 );
     44 * // returns 5
     45 */
     46 function papply( fcn ) {
     47 	var pargs;
     48 	var i;
     49 	if ( !isFunction( fcn ) ) {
     50 		throw new TypeError( 'invalid argument. First argument must be a function. Value: `' + fcn + '`.' );
     51 	}
     52 	pargs = new Array( arguments.length-1 );
     53 	for ( i = 1; i < arguments.length; i++ ) {
     54 		pargs[ i-1 ] = arguments[ i ];
     55 	}
     56 	return papplied;
     57 
     58 	/**
     59 	* Partially applied function.
     60 	*
     61 	* @private
     62 	* @param {...*} [args] - function arguments
     63 	* @returns {*} partially applied function result
     64 	*/
     65 	function papplied() {
     66 		var args;
     67 		var j;
     68 		args = pargs.slice();
     69 		for ( j = 0; j < arguments.length; j++ ) {
     70 			args.push( arguments[ j ] );
     71 		}
     72 		return fcn.apply( null, args );
     73 	}
     74 }
     75 
     76 
     77 // EXPORTS //
     78 
     79 module.exports = papply;