Design & Download
Your JS Library
in Seconds!!!

Snippet: setArgs() - Partial Application

Written by Christopher West (cwest) on November 07, 2015.
Set specific arguments in a function. Unlike YourJS.partial(), this function allows us to specify the exact argument indices we want to predefine.
function setArgs(fn, objPreArgs) {
  var n, arrPreArgIsSet = [];
  for (var k in objPreArgs) {
    n = parseInt(k, 10);
    if (n >= 0 && has(objPreArgs, n)) {
      arrPreArgIsSet[n] = true;
    }
  }
  var lOuter = arrPreArgIsSet.length;

  return function() {
    var arrArgs = [], arrPostArgs = slice(arguments), lInner = arrPostArgs.length;
    for (var iOuter = 0, iInner = 0; iOuter < lOuter; iOuter++) {
      arrArgs[iOuter] = arrPreArgIsSet[iOuter] ? objPreArgs[iOuter] : arrPostArgs[iInner++];
    }
    return fn.apply(this, arrArgs.concat(arrPostArgs.slice(iInner)));
  };
}

setArgs(...) API Documentation

Description

Gives us the ability to set specific arguments in a function. Unlike YourJS.partial(), this function allows us to specify the exact argument indices we want to predefine.

Parameters

  1. fn {Function}:
    Function to be called with the modified arguments.
  2. objPreArgs {Array|Object}:
    Array or object whose values will be sent as arguments to fn at the specified indices.

Returns

Returns a function which will call fn with the predefined arguments at their specified indices. Any arguments passed to this function will be used to fill in the arguments that were not predefined.

Examples

Here is a simple example in which we predefine the 2nd and 3rd argument of YourJS.typeOf():
var isNumOrStr = YourJS.setArgs(YourJS.typeOf, { 1: 'Number', 2: 'String' });
console.log(isNumOrStr(0));      // -> true
console.log(isNumOrStr('Cool')); // -> true
console.log(isNumOrStr(NaN));    // -> true
console.log(isNumOrStr([5]));    // -> false
Here is an example of combining this with the YourJS.get() function to make specific property getters:
var getLength = YourJS.setArgs(YourJS.get, { 1: 'length' });
console.log(getLength('Hello world!'));   // -> 12
console.log(getLength(['Hello world!'])); // -> 1