Created
July 2, 2014 14:37
-
-
Save emlun/fb3e9f562c5f950bb693 to your computer and use it in GitHub Desktop.
_.group
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* <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"); | |
* => [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); | |
* => [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