Last active
July 25, 2016 23:03
-
-
Save mdrmtz/281078f7ed314ab9c740a98eb86fdcc3 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
| /*Using a Memo to Avoid Repetitious Calculation*/ | |
| (function() { | |
| function calcFibonacci(n, memo) { | |
| // If we've got the answer in our memo, no need to recalculate | |
| if (memo[n] !== -1) { | |
| return memo[n]; | |
| } | |
| // Otherwise, calculate the answer and store it in memo | |
| memo[n] = calcFibonacci(n - 2, memo) + calcFibonacci(n - 1, memo); | |
| // We still need to return the answer we calculated | |
| return memo[n]; | |
| } | |
| function fib(n) { | |
| var memo = new Array(n + 1).fill(-1); | |
| memo[0] = 0; | |
| memo[1] = 1; | |
| return calcFibonacci(n, memo); | |
| } | |
| console.log(fib(5)); | |
| console.log(fib(11)); | |
| console.log(fib(17)); | |
| console.log(fib(31)); | |
| })(); |
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() { | |
| var util = { | |
| fib: function(n) { | |
| var memo = new Array(n + 1).fill(-1); | |
| memo[0] = 0 | |
| memo[1] = 1 | |
| return util.calcFibonacci(n, memo) | |
| }, | |
| calcFibonacci: function(n, memo) { | |
| // If we've got the answer in our memo, no need to recalculate | |
| if (memo[n] != -1) { | |
| return memo[n] | |
| } | |
| // Otherwise, calculate the answer and store it in memo | |
| memo[n] = this.calcFibonacci(n - 2, memo) + this.calcFibonacci(n - 1, memo) | |
| // We still need to return the answer we calculated | |
| return memo[n] | |
| } | |
| }; | |
| console.log(util.fib(5)); | |
| console.log(util.fib(11)); | |
| console.log(util.fib(17)); | |
| console.log(util.fib(31)); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment