Created
July 22, 2016 08:41
-
-
Save spoike/697b34a14896df4f4b8bdd9d4a89bbb1 to your computer and use it in GitHub Desktop.
Simple implementation of a curry for teaching purposes
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
/* | |
* curry(fn: Function) => Function | |
* Simple implementation of currying a function | |
* Drawbacks: | |
* - Cannot be reused as stored args is mutable | |
* - Cannot use placeholders | |
* - Will not check argument overflow | |
*/ | |
function curry(fn) { | |
var arity = fn.length; // check the arity of the given function | |
var args = []; // store all arguments here | |
function curried() { // the curried function | |
args = args.concat(Array.prototype.slice.call(arguments)); | |
if (arity <= args.length) { | |
return fn.apply(null, args); // call the function with all the arguments | |
} | |
return curried; // otherwise return the curried function to be given more arguments | |
} | |
return curried; | |
} |
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 example = (a, b, c) => a + b + c; | |
console.log(curry(example)(1)(2)); // => function | |
console.log(curry(example)(1, 2)); // => function | |
console.log(curry(example)(1)(2)(3)); // => 6 | |
console.log(curry(example)(1)(2, 3)); // => 6 | |
console.log(curry(example)(1, 2)(3)); // => 6 | |
console.log(curry(example)(1, 2, 3)); // => 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment