Skip to content

Instantly share code, notes, and snippets.

@marekdano
Created June 10, 2019 15:19
Show Gist options
  • Save marekdano/4ef2427147d7871f4a73c6bf38ac2a49 to your computer and use it in GitHub Desktop.
Save marekdano/4ef2427147d7871f4a73c6bf38ac2a49 to your computer and use it in GitHub Desktop.
// referency https://www.interviewcake.com/concept/javascript/memoization
class Fibber {
constructor() {
this.memo = {};
}
fib(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})`);
const result = this.fib(n - 1) + this.fib(n - 2);
// Memoize
this.memo[n] = result;
return result;
}
}
new Fibber().fib(5)
// computing fib(5)
// computing fib(4)
// computing fib(3)
// computing fib(2)
// grabbing memo[2]
// grabbing memo[3]
// 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment