Created
April 7, 2015 04:27
-
-
Save jamesdavidson/dc7dc1ac23b691f4aa68 to your computer and use it in GitHub Desktop.
Recursion is fun! Node javascript factorial, sync and async.
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
| module.exports = function (n,cb) { | |
| function helper (sum,i) { | |
| if (i == 0) return cb(sum); | |
| else process.nextTick( helper.bind(null,sum*i,i-1) ); | |
| }; | |
| return helper(1,n); | |
| } |
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
| module.exports = factorial; | |
| function factorial (n) { | |
| if (n == 0) return 1; | |
| else return n * factorial (n - 1); | |
| } |
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
| require('async').series([ | |
| syncTestCase.bind(null,5,120), | |
| asyncTestCase.bind(null,5,120), | |
| syncTestCase.bind(null,0,1), | |
| asyncTestCase.bind(null,0,1), | |
| syncTestCase.bind(null,1,1), | |
| asyncTestCase.bind(null,1,1), | |
| syncTestCase.bind(null,4,24), | |
| asyncTestCase.bind(null,4,24), | |
| ], function(err,data) { if (err) throw 'tests failed'; }) | |
| function syncTestCase(input,output,callback) { | |
| process.nextTick(callback.bind(null,output!=(require('./sync-factorial.js')(input)))); | |
| } | |
| function asyncTestCase(input,output,callback) { | |
| require('./async-factorial.js')(input,(function (result) { return callback(result!=output); })) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://raganwald.com/2013/03/28/trampolines-in-javascript.html