Design & Download
Your JS Library
in Seconds!!!

Snippet: restParam()

Written by Christopher West (cwest) on November 09, 2015.
Creates a wrapper function which calls the wrapped function with all of the arguments after a certain point passed in as the last argument as an array.
function restParam(fn, opt_start) {
  opt_start = opt_start == undefined ? fn.length - 1 : opt_start;
  return function() {
    var args = slice(arguments, 0, opt_start);
    args.push(slice(arguments, opt_start));
    return fn.apply(this, args);
  }
}

The concept of a rest parameter was introduced in ES6. It is basically a the summary of all of the passed parameters after the last normal one. Imagine that we have a function defined as this:

function fn(a, b, ...theRest) {
  // code
}

If we called fn(1,2,3,4,5,6), a would be 1, b would be 2 and theRest would be [3,4,5,6]. Now, with YourJS.restParam() we can do pretty much the same thing in JS engines that dont allow ES6:

YourJS.restParam(function(a, b, theRest) {
}, 2);

restParam(fn [, opt_start=fn.length-1]) API Documentation

Parameters

  1. fn {Function}:
    The function to call with the normal parameters followed by the rest parameter in its place as specified by opt_start.
  2. opt_start {number}:
    Optional. Defaults to fn.length - 1. The index within the parameters passed to the returned function that will start the summary of the rest parameter.

Returns

Returns a function that when invoked will call fn, but if there are any that have an index greater or equal to opt_start they will be passed in as the last parameter which will be an array.