Last active
December 14, 2015 00:59
-
-
Save haiiro-shimeji/5002479 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| (function() { | |
| var curry = function(f) { | |
| var c = function(l, args) { | |
| return function(a) { | |
| switch(l) { | |
| case 1: | |
| args.push(a) | |
| case 0: | |
| return f.apply(this, args) | |
| default: | |
| args.push(a) | |
| return c(l-1, args) | |
| } | |
| } | |
| } | |
| return c(f.length, []) | |
| } | |
| test("curry 0 argument", function() { | |
| var curried = curry(function() { | |
| return 10 | |
| }) | |
| equal(curried(), 10) | |
| }) | |
| test("curry 1 argument", function() { | |
| var curried = curry(function(a) { | |
| return a | |
| }) | |
| equal(curried(1), 1) | |
| }) | |
| test("curry 2 arguments", function() { | |
| var curried = curry(function(a, b) { | |
| return a + b | |
| }) | |
| //equal(curried(1), function(b) {}) | |
| equal(curried(1)(2), 3) | |
| equal(curried(1)(2), 3) //ensure that curried has no state. | |
| }) | |
| test("curry 3 arguments", function() { | |
| var curried = curry(function(a, b, c) { | |
| return a * b * c | |
| }) | |
| equal(curried(1)(2)(3), 6) | |
| }) | |
| var flip = function(curried) { | |
| return function(a) { | |
| return function(b) { | |
| return curried(b)(a) | |
| } | |
| } | |
| } | |
| /* this will causes error. | |
| test("flip 0 arguments", function() { | |
| equal( | |
| flip(curry(function() { | |
| return 10 | |
| }))(), | |
| 10 | |
| ) | |
| }) | |
| */ | |
| /* this will causes error. | |
| test("flip 1 arguments", function() { | |
| equal( | |
| flip(curry(function(a) { | |
| return a | |
| }))(3), | |
| 3 | |
| ) | |
| }) | |
| */ | |
| test("flip 2 arguments", function() { | |
| equal( | |
| flip(curry(function(a, b) { | |
| return a - b | |
| }))(3)(5), | |
| 5 - 3 | |
| ) | |
| }) | |
| test("flip 3 arguments", function() { | |
| equal( | |
| flip(curry(function(a, b, c) { | |
| return a - b * c | |
| }))(3)(5)(10), | |
| 5 - 3 * 10 | |
| ) | |
| }) | |
| })() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment