Last active
December 10, 2015 12:28
-
-
Save AutoSponge/4434651 to your computer and use it in GitHub Desktop.
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
/** | |
* @method curry | |
* @memberOf Function.prototype | |
* @param arg {Any} | |
* @param context {Object} used as /this/ when invoking the original function | |
* @returns {Function} | |
* @example var add1 = (function add(a, b) { return a + b; }).curry(1); | |
* add1(2);//3 | |
* @see http://en.wikipedia.org/wiki/Currying | |
*/ | |
Function.prototype.curry = function (arg, context) { | |
var f = this; | |
return function () { | |
var args = [arg]; | |
for (var i = 0, len = arguments.length; i < len; i += 1) { | |
args[i + 1] = arguments[i]; | |
} | |
return f.apply(context || this, args); | |
}; | |
}; |
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
curry = function (fn, arg, context) { | |
return function () { | |
var args = [arg]; | |
for (var i = 0, len = arguments.length; i < len; i += 1) { | |
args[i + 1] = arguments[i]; | |
} | |
return fn.apply(context || this, args); | |
}; | |
}; | |
function add(a, b, c) { return a + b + c; } | |
var add1 = curry(add, 1); | |
var add2 = curry(add1, 2); | |
add2(3); | |
/*also*/ | |
curry(curry(add, 1), 2)(3); | |
/*also*/ | |
curry(add, 1)(2, 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment