Last active
September 7, 2021 21:39
-
-
Save mkuklis/5294248 to your computer and use it in GitHub Desktop.
auto curry in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
Here's one that passes the args
state down the recursion instead of closing over it, making @casperin's example work
This works too. Just re-bind the function on every application. Pretty pure curry implementation.
@djtriptych your version does not support this
reinjection:
let add = autocurryByMkuklis(function (a, b, c, d) {
console.log(this);
return a + b + c + d;
});
let add2 = autocurryByDjtriptych(function (a, b, c, d) {
console.log(this);
return a + b + c + d;
});
add(1).apply(42, [2, 3, 4]); // `this` is 42
add2(1).apply(42, [2, 3, 4]); // `this` is null
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
Really nicely condensed.