Created
December 26, 2018 05:14
-
-
Save yanzhihong23/b5e3d5ce3b7bcb6dd81d4ac59a160e40 to your computer and use it in GitHub Desktop.
curry multi add
This file contains hidden or 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 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