Skip to content

Instantly share code, notes, and snippets.

@Artanis
Created September 8, 2011 00:08
Show Gist options
  • Save Artanis/1202231 to your computer and use it in GitHub Desktop.
Save Artanis/1202231 to your computer and use it in GitHub Desktop.
Memoized, naïve, recursive Fibonacci function in JavaScript
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