Skip to content

Instantly share code, notes, and snippets.

@jeffschwartz
Last active August 29, 2015 13:56
Show Gist options
  • Save jeffschwartz/9221031 to your computer and use it in GitHub Desktop.
Save jeffschwartz/9221031 to your computer and use it in GitHub Desktop.
A JavaScript implementation of curry.
(function(){
"use strict";
/**
* A factory for creating curry functions that
* are tied to the arrity of the function f.
*/
function makeArrityBasedCurry(n) {
var curry = function(f){
var args = [].slice.call(arguments, 1);
//Enforce f must be a function.
if(typeof f !== "function"){
throw new Error("f must be a function");
}
return function(){
var largs = args.concat([].slice.call(arguments, 0));
if(largs.length >= n){
return f.apply(this, largs);
}else{
largs.unshift(f);
return curry.apply(this, largs);
}
};
};
return curry;
}
/**
* Augment Function's prototype to support creating curried functions.
*/
Function.prototype.curry = function(nParams){
//If nParams is not provided ask "this" how many parameters it has.
var arrity = nParams ? nParams : this.length;
return makeArrityBasedCurry(arrity)(this);
};
/**
* A function to be curried.
* It is expecting 4 arguments when it is called.
*/
var curry4 = function f(a, b, c, d) {
return a + b + c + d;
}.curry();
/**
* Make a curry whose target function f has an arity of 4.
*/
var result;
result = curry4(1)(2, 3, 4);
console.log(result);
result = curry4(1, 2)(3, 4);
console.log(result);
result = curry4(1, 2, 3)(4);
console.log(result);
result = curry4(1, 2, 3, 4);
console.log(result);
/// Since curry4 returns a function it can also be used as follows.
result = curry4(1)(1)(1)(1);
console.log(result);
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment