Skip to content

Instantly share code, notes, and snippets.

@jordanrios94
Created February 1, 2023 05:11
Show Gist options
  • Save jordanrios94/12c0e5118622243ae0e2367519beb044 to your computer and use it in GitHub Desktop.
Save jordanrios94/12c0e5118622243ae0e2367519beb044 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 preceding two.
// Iterative Fib (Linear runtime)
function fibItr(n) {
const result = [0, 1];
for (let i = 2; i <= n; i++) {
const a = result[n - 1];
const b = result[n - 2];
result.push(a + b);
}
return result[result.length - 1];
}
// Recursive Fib (Quadratic runtime)
function fib(n) {
if (n < 2) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
// Memoized Fib
function memoize(fn) {
const cache = {};
return function(...args) {
if (cache[args]) {
return cache[args];
}
const result = fn.apply(this, args);
cache[args] = result;
return result;
}
}
function slowFib(n) {
if (n < 2) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
const fib = memoize(slowFib);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment