Created
September 8, 2011 00:08
-
-
Save Artanis/1202231 to your computer and use it in GitHub Desktop.
Memoized, naïve, recursive Fibonacci function in JavaScript
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
var memoize = function(fn, debug) { | |
var cache = {}; | |
return function() { | |
var arguments = [].slice.apply(arguments) | |
var args = JSON.stringify(arguments); | |
if(cache[args] !== undefined) { | |
if(debug === true) { | |
print("In cache: (" + args + ", " + cache[args] + ")"); | |
} | |
return cache[args]; | |
} else { | |
var value = fn.apply(this, arguments); | |
if(debug === true) { | |
print("Brand new: (" + args + ", " + value + ")"); | |
} | |
cache[args] = value; | |
return value; | |
} | |
}; | |
}; | |
var fibonacci = function(n) { | |
return n === undefined ? 0: | |
n == 0 ? 0: | |
n == 1 ? 1: | |
fibonacci(n-1) + fibonacci(n-2); | |
}; | |
fibonacci = memoize(fibonacci, true); | |
print(fibonacci(10)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment