Created
August 26, 2014 19:07
-
-
Save chrisguitarguy/7f3819f91b7827893b71 to your computer and use it in GitHub Desktop.
Function currying in JavaScript. Kind of.
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 makeCurry(callable) { | |
return function () { | |
var args = []; | |
function inner() { | |
args = args.concat(Array.prototype.slice.call(arguments)); | |
if (args.length >= callable.length) { | |
return callable.apply(callable, args); | |
} | |
return inner; | |
} | |
return inner.apply(inner, arguments); | |
}; | |
} | |
function add(x, y, z) { | |
return x + y + z; | |
} | |
var curryAdd = makeCurry(add); | |
console.log(curryAdd(1)(2)(3)) | |
function sub(x, y, z) { | |
return x - y - z; | |
} | |
var currySub = makeCurry(sub); | |
console.log(currySub(10)(1)(2)); | |
console.log(currySub(10, 1)(2)); | |
console.log(currySub(10, 2, 1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment