Last active
October 30, 2015 20:28
-
-
Save felipecwb/b8543c78e274051c3354 to your computer and use it in GitHub Desktop.
Fibonacci in Javascript with recursion and cache.
This file contains hidden or 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
#!/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