Skip to content

Instantly share code, notes, and snippets.

@rk
Created October 3, 2011 13:07
Show Gist options
  • Save rk/1259066 to your computer and use it in GitHub Desktop.
Save rk/1259066 to your computer and use it in GitHub Desktop.
Cached fibonacci
var http = require('http');
function fib(n){
if (n < 2) return 1;
else return fib(n-2) + fib(n-1);
}
var cached_fib = (function(){
var cache = {};
return function(n) {
if (cache[n]) return cache[n];
else return cache[n] = fib(n);
}
})();
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(cached_fib(40).toString());
}).listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment