Skip to content

Commit

Permalink
[Recursion with Memoize] StephenGrider#13 Complete
Browse files Browse the repository at this point in the history
  • Loading branch information
Brett Dawidowski committed Apr 4, 2019
1 parent 36cdd41 commit 881f793
Showing 1 changed file with 36 additions and 13 deletions.
49 changes: 36 additions & 13 deletions exercises/fib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,28 +10,51 @@


// O(n)
function fib(n) {
// Always know the first two will be 0, 1
const results = [0, 1];
// function fib(n) {
// // Always know the first two will be 0, 1
// const results = [0, 1];

// Increase next item by adding the two pervious items together [5, 8, 13]
for (let i = 2; i <= n; i++){
let a = results[i - 1];
let b = results[i - 2];
// // Increase next item by adding the two pervious items together [5, 8, 13]
// for (let i = 2; i <= n; i++){
// let a = results[i - 1];
// let b = results[i - 2];

// Add together and append to array
results.push(a + b);
}
return results[results.length - 1];
}
// // Add together and append to array
// results.push(a + b);
// }
// return results[results.length - 1];
// }


// O(n)
function fib(n) {
function slowFib(n) {
// n = 0 or n = 1
if (n < 2) return n;

return fib(n - 1) + fib(n - 2);
}


function memoize(fn) {
// init cache of results and args of functions already ran
const cache = {};

return (...args) => {
// if function with those params has already ran return cached result
if (cache[args]) return cache[args];

// call function with args and get response using apply
const result = fn.apply(this, args);

// store returned value with key as args
cache[args] = result;

// return that result
return result;

}
}

const fib = memoize(slowFib);

module.exports = fib;

0 comments on commit 881f793

Please sign in to comment.