Created
December 18, 2018 22:46
-
-
Save Luke-Rogerson/462352a59ef76817ee485833ccef96d8 to your computer and use it in GitHub Desktop.
Print out the n-th entry in the fibonacci series. The fibonacci series is an ordering of numbers where each number is the sum of the preceeding two. For example, the sequence [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] forms the first ten entries of the fibonacci series. Example: fib(4) === 3
This file contains 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
// Memoize to make more performant | |
function memoize(func) { | |
const cache = {}; | |
return function(...args) { | |
if (cache[args]) return cache[args]; | |
const result = func.apply(this, args); | |
cache[args] = result; | |
return result; | |
}; | |
} | |
// Recursive solution | |
function fib(n) { | |
if (n < 2) return n; | |
return fib(n - 1) + fib(n - 2); | |
} | |
fib = memoize(fib); | |
// Iterative solution | |
// function fib(n) { | |
// const results = [0, 1]; | |
// for (let i = 2; i <= n; i++) { | |
// results.push(results[i - 1] + results[i - 2]); | |
// } | |
// return results[n]; | |
// } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment