Last active
August 9, 2017 14:30
-
-
Save krose422/082fbb74d0941b0adfe8e2abcb62db21 to your computer and use it in GitHub Desktop.
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
function Fibber() { | |
this.memo = {}; | |
} | |
Fibber.prototype.fib = function(n) { | |
if (n < 0) { | |
throw new Error('Index was negative. No such thing as a negative index in a series.'); | |
// base cases | |
} else if (n === 0 || n === 1) { | |
return n; | |
} | |
// see if we've already calculated this | |
if (this.memo.hasOwnProperty(n)) { | |
console.log('grabbing memo[' + n + ']'); | |
return this.memo[n]; | |
} | |
console.log('computing fib(' + n + ')'); | |
var result = this.fib(n - 1) + this.fib(n - 2); | |
// memoize | |
this.memo[n] = result; | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment