Skip to content

Instantly share code, notes, and snippets.

@krose422
Last active August 9, 2017 14:30
Show Gist options
  • Save krose422/082fbb74d0941b0adfe8e2abcb62db21 to your computer and use it in GitHub Desktop.
Save krose422/082fbb74d0941b0adfe8e2abcb62db21 to your computer and use it in GitHub Desktop.
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