Created
September 7, 2012 07:13
-
-
Save puffnfresh/3664037 to your computer and use it in GitHub Desktop.
Support for both curried and uncurried application in functional 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 curry(f) { | |
return function(x) { | |
var g = f.bind(this, x); | |
if(g.length == 0) return g(); | |
if(arguments.length > 1) return curry(g).apply(this, [].slice.call(arguments, 1)); | |
return curry(g); | |
}; | |
} | |
var sum = curry(function(x, y) { | |
return x + y; | |
}); | |
var incr = sum(1); | |
console.log(incr(2)); | |
console.log(sum(1)(2)); | |
console.log(sum(1, 2)); | |
var tuple4 = curry(function(a, b, c, d) { | |
return [a, b, c, d]; | |
}); | |
console.log(tuple4(1)(2, 3, 4)); | |
console.log(tuple4(1, 2)(3, 4)); | |
console.log(tuple4(1, 2)(3)(4)); | |
console.log(tuple4(1, 2, 3)(4)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment