Skip to content

Instantly share code, notes, and snippets.

@AutoSponge
Last active December 10, 2015 12:28
Show Gist options
  • Save AutoSponge/4434651 to your computer and use it in GitHub Desktop.
Save AutoSponge/4434651 to your computer and use it in GitHub Desktop.
/**
* @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);
};
};
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