Last active
May 17, 2016 21:59
-
-
Save griffinmichl/a53a3b4caab45c320f80d7992d4f9ac8 to your computer and use it in GitHub Desktop.
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
function sum(numbers, i = 0) { | |
if (i === numbers.length) { | |
return 0 | |
} | |
return numbers[i] + sum(numbers, i+1) | |
} | |
console.log(sum([1,2,3,4,5])) | |
function sumTail(numbers, i = 0, sum = 0) { | |
if (i === numbers.length) { | |
return sum | |
} | |
return sumTail(numbers, i+1, sum + numbers[i]) | |
} | |
console.log(sumTail([1,2,3,4,5])) | |
function factorial(n) { | |
if (n === 1) { | |
return 1 | |
} | |
return n * factorial(n-1) | |
} | |
console.log(factorial(10)) | |
function factorialTail(n, fact = 1) { | |
if (n === 1) { | |
return fact | |
} | |
return factorialTail(n-1, fact * n) | |
} | |
console.log(factorial(10)) | |
function fibonacci(n, memo = []) { | |
if (n < 2) { | |
return n | |
} | |
if (!memo[n]) { | |
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo) | |
} | |
return memo[n] | |
} | |
console.log(fibonacci(100)) | |
function fibonacciTail(n, current = 0, next = 1) { | |
if (n === 0) { | |
return current | |
} | |
return fibonacciTail(n-1, next, current + next) | |
} | |
console.log(fibonacciTail(100)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment