Created
June 23, 2009 23:21
-
-
Save igstan/134907 to your computer and use it in GitHub Desktop.
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
/** | |
* A JavaScript utility for function currying. Inspired by Haskell's built-in | |
* currying feature. Example: | |
* | |
* var adder = curry(function (a, b, c) { | |
* return a + b + c; | |
* }); | |
* | |
* var add_10 = adder(10); | |
* var add_20 = add_10(10); | |
* | |
* print(add_20(10)); // prints 30 | |
* | |
* @see http://en.wikipedia.org/wiki/Currying | |
* @author Ionut G. Stan <ionut.g.stan ~ gmail.com> | |
* @license BSD | |
*/ | |
var curry = function (f) { | |
var array = Array.slice, | |
prevArity = arguments[1] || f.length; | |
return function () { | |
var args = array(arguments), | |
currArity = args.length; | |
if (currArity >= prevArity) { | |
return f.apply(this, args); | |
} | |
return curry(function () { | |
return f.apply(this, args.concat(array(arguments))); | |
}, prevArity - currArity); | |
}; | |
}; | |
/** | |
* Specs using the jSpec library. | |
* | |
* @see http://github.com/igstan/jSpec/tree/master | |
*/ | |
if (typeof jSpec !== "undefined") { | |
$.describe("The curry() function", function () { | |
$.it("should curry one argument functions", function () { | |
var unary = curry(function (a) { | |
return a; | |
}); | |
var result = unary(1); | |
$(result).should.equal(1); | |
}); | |
$.it("should curry multi argument functions", function () { | |
var nary = curry(function (a, b) { | |
return a + b; | |
}); | |
var result = nary(1)(2); | |
$(result).should.equal(3); | |
}); | |
$.it("should curry multi argument functions", function () { | |
var nary = curry(function (a, b, c) { | |
return a + b + c; | |
}); | |
var result = nary(1, 2)(3); | |
$(result).should.equal(6); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment