Skip to content

Instantly share code, notes, and snippets.

@johnteee
Created June 28, 2018 04:36
Show Gist options
  • Select an option

  • Save johnteee/481e6c316f1f46f01ab97e511954057b to your computer and use it in GitHub Desktop.

Select an option

Save johnteee/481e6c316f1f46f01ab97e511954057b to your computer and use it in GitHub Desktop.
fib.js
function fibonacci(n) {
return Math.round((Math.pow((1 + Math.sqrt(5)) / 2, n) - Math.pow(-2 / (1 + Math.sqrt(5)), n)) / Math.sqrt(5));
}
function trampoline(f) {
return function (...args){
var result = f( ...args )
while (typeof result === "function") {
result = result()
}
return result
}
}
function fib (n) {
return trampoline(function inner_fib(n, a, b) {
if (n === 0) {return a;}
if (n === 1) {return b;}
return () => inner_fib(n - 1, b, a + b);
})(n, 0, 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment