Last active
December 22, 2015 02:59
-
-
Save cdcme/6406954 to your computer and use it in GitHub Desktop.
Fast fibonacci in nodejs using caching
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
/* in routes/fib.js */ | |
var cache = new Array(); | |
function fib(n) { | |
if(n.toString() in cache) | |
return cache[n.toString()]; | |
if(n < 2) { return 1; } | |
else { | |
var fibB = fib(n - 2) + fib(n - 1); | |
cache[n.toString()] = fibB; | |
return fibB; | |
} | |
} | |
exports.getFib = function(req, res) { | |
console.log(req.params); | |
var n = req.params.num; | |
console.log('Calculate fibonacci for ' + n); | |
console.time('fib'); | |
var result = fib(n); | |
console.timeEnd('fib'); | |
res.jsonp(result); | |
} |
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
var fib = require('./fib'); | |
/** | |
* Set up routes | |
*/ | |
module.exports = function(app, options) { | |
app.get('/fib/:num', fib.getFib); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment