Skip to content

Instantly share code, notes, and snippets.

@cdcme
Last active December 22, 2015 02:59
Show Gist options
  • Save cdcme/6406954 to your computer and use it in GitHub Desktop.
Save cdcme/6406954 to your computer and use it in GitHub Desktop.
Fast fibonacci in nodejs using caching
/* 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);
}
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