Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
_.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
You can’t perform that action at this time.