Skip to content

Instantly share code, notes, and snippets.

@felipecwb
Last active October 30, 2015 20:28
Show Gist options
  • Save felipecwb/b8543c78e274051c3354 to your computer and use it in GitHub Desktop.
Save felipecwb/b8543c78e274051c3354 to your computer and use it in GitHub Desktop.
Fibonacci in Javascript with recursion and cache.
#!/usr/bin/env node
"use strict";
var fibonacci = function fib(n) {
if (typeof fib._cache === 'undefined') {
fib._cache = {};
}
if (fib._cache[n]) {
return fib._cache[n];
}
return fib._cache[n] = (n > 1) ? fib(n -1) + fib(n - 2) : n;
};
var args = global.process.argv.slice(2);
try {
console.log(fibonacci(args[0]));
} catch (e) {
console.log(e.toString());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment