Skip to content

Instantly share code, notes, and snippets.

@spoike
Created July 22, 2016 08:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save spoike/697b34a14896df4f4b8bdd9d4a89bbb1 to your computer and use it in GitHub Desktop.
Save spoike/697b34a14896df4f4b8bdd9d4a89bbb1 to your computer and use it in GitHub Desktop.
Simple implementation of a curry for teaching purposes
/*
* 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;
}
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