Skip to content

Instantly share code, notes, and snippets.

@azurite
Created May 30, 2017 19:24
Show Gist options
  • Save azurite/7a50c1156cf1afc6a775441f7778b518 to your computer and use it in GitHub Desktop.
Save azurite/7a50c1156cf1afc6a775441f7778b518 to your computer and use it in GitHub Desktop.
A small demonstrarion of a general curry function
function curry(fn) {
var slice = Array.prototype.slice;
var arity = fn.length;
var args = slice.call(arguments, 1);
function acc() {
var largs = args;
if (arguments.length > 0) {
largs = largs.concat(slice.call(arguments, 0));
}
if(largs.length >= arity) {
return fn.apply(this, largs);
}
else {
return curry.apply(this, [fn].concat(largs));
}
};
return args.length >= arity ? acc() : acc;
};
function add(a, b, c, d, e, f) {
return a + b + c + d + e + f;
}
var curryAdd = curry(add);
console.log(curryAdd(1)(2)(3)(4)(5)(6) === add(1, 2, 3, 4, 5, 6)); // true
console.log(curryAdd(1)(2)(3)(4)(5)(6) === curryAdd(1, 2, 3, 4, 5, 6)); // true
console.log(curryAdd(1, 2)(3)(4)(5, 6) === curryAdd(1, 2, 3, 4)(5)(6)); // true
console.log(curryAdd(1)(2)(3, 4, 5, 6) === curryAdd(1, 2, 3, 4)(5)(6)); // true
// and so on...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment