Design & Download
Your JS Library
in Seconds!!!

Snippet: partial() - Partial Application

Written by Christopher West (cwest) on November 07, 2015.
Presets the left-most arguments in a function.
function partial(fn) {
  var arrArgs = slice(arguments, 1);
  fn = getSimpleCallback(fn);
  return function() {
    return fn.apply(this, arrArgs.concat(slice(arguments)));
  };
}

A nice utility function to have because it gives us the ability to preset the left-most arguments in a function:

function sum(a) {
  for (var i = 1; i < arguments.length; i++) {
    a += arguments[i];
  }
  return a;
}

var addTo10 = YourJS.partial(sum, 10);
console.log(addTo10(20));  // Results in 30
console.log(addTo10(40));  // Results in 40

Parameters

  1. fn {Function}
    The function that will be called with the preset arguments.
  2. arg1 {*}
    The first argument to be sent to fn.
  3. ...argN {*}
    Each additional argument to be sent to fn will be a separate argument.

Returns

The new function which when called will call fn with the specified arguments filled in.