Skip to content

Instantly share code, notes, and snippets.

@emlun
Created July 2, 2014 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emlun/fb3e9f562c5f950bb693 to your computer and use it in GitHub Desktop.
Save emlun/fb3e9f562c5f950bb693 to your computer and use it in GitHub Desktop.
_.group
/**
* <p>
* <code>_.group(functions, [context])</code>
* </p>
* <p>
* <code>_.group(*functions)</code>
* </p>
*
* <p>
* Returns a function <code>f</code> that wraps an array of functions and
* calls them as a group. Whenever <code>f</code> is called, it will call the
* grouped functions in sequence with the same arguments, and return their
* return values in an array.
* </p>
*
* <p>
* The grouped functions are bound to the <code>context</code> object, if one
* is passed.
* </p>
*
* <p>
* If <code>context</code> is omitted, then the functions to group can be
* passed as individual arguments, as in example 2.
* </p>
*
* <p>
* Example 1
* <pre>
* <code>
* var f1 = function() { return this; };
* var f2 = function(a) { return this.foo + a; };
* _.group([f1, f2], { foo: "foo" })("bar");
* =&gt; [Object { foo="foo" }, "foobar"]
* </code>
* </pre>
* </p>
*
* <p>
* Example 2
* <pre>
* <code>
* var f1 = function(a, b) { return a+b; };
* var f2 = function(a, b) { return a-b; };
* _.group(f1, f2)(3 ,5);
* =&gt; [8, -2]
* </code>
* </pre>
* </p>
*/
_.group = function() {
var functions = arguments;
var context = false;
if(_.isArray(arguments[0])) {
functions = arguments[0];
context = arguments[1];
}
return function() {
var args = arguments;
return _.map(
functions,
function(func) {
return func.apply(this, args);
},
context || this
);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment