Skip to content

Instantly share code, notes, and snippets.

@yanzhihong23
Created December 26, 2018 05:14
Show Gist options
  • Save yanzhihong23/b5e3d5ce3b7bcb6dd81d4ac59a160e40 to your computer and use it in GitHub Desktop.
Save yanzhihong23/b5e3d5ce3b7bcb6dd81d4ac59a160e40 to your computer and use it in GitHub Desktop.
curry multi add
function curry(fn) {
var res;
function curried() {
args = [].slice.call(arguments);
if (!res && args.length == fn.length) {
res = fn.apply(this, args);
return curried;
} else if (!res && args.length > fn.length) {
res = fn.apply(this, args);
return curried.apply(this, args.splice(fn.length));
} else if (res && args.length == fn.length - 1) {
res = fn.apply(this, [res].concat(args));
return curried;
} else if (res && args.length > fn.length - 1) {
res = fn.apply(this, [res].concat(args));
return curried.apply(this, args.splice(fn.length - 1));
} else {
return function() {
return curried.apply(this, args.concat([].slice.call(arguments)));
};
}
}
curried.valueOf = function() {
var _res = res;
res = null;
return _res;
};
return curried;
}
function add(a, b) {
return a + b;
}
let curriedAdd = curry(add);
curriedAdd(1)(2)(3); // 6
curriedAdd(1)(2, 3)(4, 5, 6); // 21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment