Design & Download
Your JS Library
in Seconds!!!

Snippet: fuse() - Fusing Two or More Functions

Written by Christopher West (cwest) on November 29, 2015.
Creates a wrapper function for two or more functions essentially fusing them all into one.
function fuse(fn1, fn2, opt_excludeRetArgs) {
  var fns = slice(arguments), l = fns.length;
  opt_excludeRetArgs = typeOf(fns[l - 1], 'Function') ? 0 : (l--, fns.pop());
  return function() {
    for (var arrArgs = slice(arguments), extraArgs = [], me = this, i = 0, ret; i < l; i++) {
      ret = fns[i].apply(me, arrArgs.concat(extraArgs));
      if (!opt_excludeRetArgs) {
        extraArgs.push(ret);
      }
    }
    return ret;
  };
}

fuse() API Documentation

Description

Creates a wrapper function for two or more functions essentially fusing them all into one.

Parameters

  1. fn1 {Function}:
    The first function to be called by the wrapper function.
  2. fn2 {Function}:
    The second function to be called by the wrapper function.
  3. ...opt_fnX {Function=}:
    Optional. Each function to be subsequently called after fn2 by the wrapper function.
  4. opt_excludeRetArgs {Boolean=}:
    Optional. Defaults to false. If true the arguments passed to each wrapped function will be the same as those passed to the wrapper function. If false the arguments passed to each wrapped function will start off with those passed to the wrapper function but then each subquent argument will be the return value of the previous wrapped function(s).

Returns

Returns a wrapper function which when called will execute each of the passed functions (eg. fn1, fn2, etc.) in order. The return value of the wrapper function will be the return value of the last wrapped function.