Skip to content

Instantly share code, notes, and snippets.

@mkuklis
Last active September 7, 2021 21:39
Show Gist options
  • Save mkuklis/5294248 to your computer and use it in GitHub Desktop.
Save mkuklis/5294248 to your computer and use it in GitHub Desktop.
auto curry in JavaScript
function toArray(args) {
return [].slice.call(args);
}
function autocurry(fn) {
var len = fn.length;
var args = [];
return function next() {
args = args.concat(toArray(arguments));
return (args.length >= len) ?
fn.apply(this, args.splice(0)) :
next;
}
}
// usage
var add = autocurry(function (a, b, c, d) {
return a + b + c + d;
});
add(1)(2)(3)(4); // 10
var one = add(1);
one(4, 5, 6); // 16
add(2)(3, 4)(5); // 14
@gund
Copy link

gund commented Mar 26, 2019

Fixed curry function that does not store state in scope between multiple calls (also typed for up-to 2 arguments):

export function curry<A1, R>(fn: (arg1: A1) => R): (arg1: A1) => R;
export function curry<A1, A2, R>(fn: (arg1: A1, arg2: A2) => R): (arg1: A1) => (arg2: A2) => R;
export function curry<T extends (...args: any) => any>(fn: T): (...args: any[]) => any {
  return function(...firstArgs) {
    const argsLen = fn.length;
    let allArgs = [];

    return nextArgument(...firstArgs);

    function nextArgument(...args) {
      allArgs = allArgs.concat(args);
      return allArgs.length >= argsLen ? fn.apply(this, allArgs) : nextArgument;
    }
  };
}

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