Created
July 9, 2012 20:37
-
-
Save sjoerdvisscher/3078744 to your computer and use it in GitHub Desktop.
Curry and uncurry 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
<script> | |
function curry(f) | |
{ | |
if (typeof f != "function" || f.length < 2) | |
return f; | |
return mkHelper(f, []); | |
} | |
function mkHelper(f, args) | |
{ | |
return function(a) | |
{ | |
var args1 = args.concat([a]); | |
if (args1.length == f.length) | |
return f.apply(this, args1); | |
else | |
return mkHelper(f, args1); | |
}; | |
} | |
function uncurry(f) | |
{ | |
if (typeof f != "function" || f.length == 0) | |
return f; | |
return function() | |
{ | |
var r = f; | |
for (var i = 0; i < arguments.length; i++) | |
r = r(arguments[i]); | |
return r; | |
}; | |
} | |
function test(a, b, c) | |
{ | |
return a * b * c; | |
} | |
alert(uncurry(curry(test))(3, 4, 5)); | |
alert(uncurry(curry([3,5]))); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment