Skip to content

Instantly share code, notes, and snippets.

@jamesdavidson
Created April 7, 2015 04:27
Show Gist options
  • Select an option

  • Save jamesdavidson/dc7dc1ac23b691f4aa68 to your computer and use it in GitHub Desktop.

Select an option

Save jamesdavidson/dc7dc1ac23b691f4aa68 to your computer and use it in GitHub Desktop.
Recursion is fun! Node javascript factorial, sync and async.
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);
}
module.exports = factorial;
function factorial (n) {
if (n == 0) return 1;
else return n * factorial (n - 1);
}
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); }))
}
@davidporter-id-au
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment