Skip to content

Instantly share code, notes, and snippets.

@nonlogos
Last active November 30, 2017 21:04
Show Gist options
  • Save nonlogos/d6803e4de4bcd56b1e90c172262bb996 to your computer and use it in GitHub Desktop.
Save nonlogos/d6803e4de4bcd56b1e90c172262bb996 to your computer and use it in GitHub Desktop.
fibonacci with memoisation
// 5 * 4 * 3 * 2 * 1
const factorial = (n) => {
//base case
if (n === 1) return 1;
// logic
return n * factorial(n-1);
}
console.log(factorial(5))
const fib = (n, mem) => {
// memoise
mem = mem || {};
//base case
if (n <= 1) return 1;
if (mem[n]) return mem[n];
return mem[n] = fib(n-1, mem) + fib(n-2, mem);
}
console.log(fib(5)) // return 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment