Skip to content

Instantly share code, notes, and snippets.

@saturation
Created January 18, 2014 23:56
Show Gist options
  • Save saturation/8498535 to your computer and use it in GitHub Desktop.
Save saturation/8498535 to your computer and use it in GitHub Desktop.
//see: http://mksenzov.github.io/javascript/2014/01/18/autocurry-in-js.html
// We create a function autocurry
function autocurry(fn) {
// Autocurry takes an ordinary function `fn` as an argument
// and wraps it into a `magic` function
return function /* magic */ () {
// Magic checks the amount of formal parameters fn has: fn.length
// vs. how much paramters where passed to `magic`: arguments.length
if (fn.length > arguments.length) {
// If there is not enough parameters: let's build and return
// a curried version of fn
var slice = Array.prototype.slice;
var args = slice.apply(arguments);
return function() {
return fn.apply(null, args.concat(slice.apply(arguments)));
};
}
// Otherwise let's just aply fn to arguments of `magic` and move on
return fn.apply(null, arguments);
};
}
// Basic `add` function:
function add(a, b) {
return a + b;
}
// Enable auto-curry:
var add = autocurry(add);
// Normal application
add(1, 2); // => 3
// Auto-currying:
var add1 = add(1)
typeof add1 // => [Function]
add1(24) // => 25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment