Last active
October 21, 2016 23:07
-
-
Save jokester/e9a7e3a97b55b42f08f9 to your computer and use it in GitHub Desktop.
curry 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
var curry = function(foo, arity) { | |
var curried = function() { | |
// parameters by far are passed with `this` | |
// slice()-ing it here makes the curried function stateless | |
var new_args = this.slice(); | |
for(arg_key in arguments) { | |
new_args.push(arguments[arg_key]); | |
} | |
if (new_args.length >= arity) { | |
return foo.apply(null, new_args); | |
} else { | |
return curried.bind(new_args); | |
} | |
}; | |
return curried.bind([]); | |
}; | |
var sum4 = function(a,b,c,d) { return a+b+c+d; }; | |
var curried = curry(sum4, sum4.length); | |
console.log(curried(1,2,3)(4)); | |
// -> 10 | |
console.log(curried(1)(2,3)(4)); | |
// -> 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment