Skip to content

Instantly share code, notes, and snippets.

@briancavalier briancavalier/curry.js forked from unscriptable/curry.js
Last active Aug 29, 2015

Embed
What would you like to do?
module.exports = curry;
function curry (f) {
var arity = f.length;
var params = [];
var end = createEnd(f, arity);
return createCurried(params, arity, end);
}
function createEnd (f, arity) {
var src = 'return function ' + f.name + '_curried (args) { return f(';
for (var i = 0; i < arity; i++) {
src += (i ? ', args[' : 'args[') + i + ']';
}
src += '); };';
return (new Function ('f', src)(f));
}
function createCurried (collected, arity, end) {
return function () {
var params = concat(collected, arguments);
return params.length < arity
? createCurried(params, arity, end)
: end(params);
};
}
function concat(a, b) {
var al = a.length;
var bl = b.length;
var c = new Array(al + bl);
var i;
for(i=0; i<al; ++i) {
c[i] = a[i];
}
for(i=0; i<bl; ++i) {
c[i+al] = b[i];
}
return c;
}
function add(x, y) {
return x + y;
}
var addc = curry(add);
var z = addc(1)(2);
console.log(z);
@briancavalier

This comment has been minimized.

Copy link
Owner Author

commented Aug 1, 2014

This variant of @unscriptable's original version uses an extra dynamic compilation wrapper (line 16), to allow naming the last function in the curry chain, which could make debugging easier. It probably has similar perf characteristics.

@briancavalier

This comment has been minimized.

Copy link
Owner Author

commented Aug 1, 2014

Update: I added a hand-coded concat() for appending arguments. It's significantly faster than using Array.prototype.concat + slice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.