Skip to content

Instantly share code, notes, and snippets.

@bigs
Last active December 13, 2015 17:38
Show Gist options
  • Save bigs/4949010 to your computer and use it in GitHub Desktop.
Save bigs/4949010 to your computer and use it in GitHub Desktop.
A cute currying function written in pure JavaScript for FUNZIES.
var curry = function (f, args, binding) {
if (typeof f !== 'function' ||
toString.call(args) !== '[object Array]') {
throw new Error('Invalid parameters');
return;
}
if (typeof binding !== 'object') {
binding = this;
}
return function () {
var _args = args.concat(Array.prototype.slice.call(arguments));
return f.apply(binding, _args);
};
};
// Example usage
var add = function(x, y, z) {
return x + y + z;
};
var addTwo = curry(add, [2]);
console.log(addTwo(4, 6)); // 12
console.log(addTwo(1, 3)); // 6
var addTwoAndFour = curry(add, [2, 4]);
console.log(addTwoAndFour(6)); // 12 as well!
@wyattanderson
Copy link

Array.isArray

@aib
Copy link

aib commented Feb 14, 2013

I was brainstorming how to refine my own curry function when someone mentioned Function.prototype.bind...

Copy link

ghost commented Feb 14, 2013

function curry(f, args){
    return f.length > 1 ? function(){
        var params = args ? args.concat() : [];
        return params.push.apply(params, arguments) < f.length && arguments.length ?
            curry.call(this, f, params) : f.apply(this, params);
    } : f;
}

var add = curry(function(x,y){
    return x + y;
});

var addTwo = add(2);
console.log(addTwo(3));

@bergmark
Copy link

> Function.prototype.betterBind = function (scope, arg1) {
  var args = Array.prototype.slice.call(arguments, 1);
  var func = this;
  return function () {
    return Function.prototype.apply.call(
      func,
      scope === null ? this : scope,
      args.concat(Array.prototype.slice.call(arguments)));
  };
};
Function.prototype.curry = Function.prototype.betterBind.betterBind(null, null);

> (function (x,y) { return x + y }).curry(1).curry(2)()
3

> (function (x,y) { return x + y }).curry(1,2)()
3

@bigs
Copy link
Author

bigs commented Feb 14, 2013

awesome feedback/code, guys! always amazed by the number of unique solutions to problems in js.

@wyattanderson i don't think that is universally supported? if so, could have saved some time!

@alb i discovered that shortly after the brief exercise — it often times works out that way.. thanks for the link.

@pabloPXL read that one over a few times — nifty implementation.

@bergmark lovely, thanks.

@bigs
Copy link
Author

bigs commented Feb 14, 2013

made a final edit with some of your suggestions/hints

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment