Last active
October 8, 2018 06:39
-
-
Save junjchen/86b0b8bbd20e17b3f3b5491fbaa7d1f9 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 factorial(num) { | |
if(num <= 1) return num; | |
return num * factorial(--num); | |
} | |
function factorialSmart(num) { | |
function factorial(acc, num) { | |
if(num <=1) return acc; | |
return function() { return factorial(acc * num, --num); } | |
} | |
function trampoline(func) { | |
var result = func; | |
while(result && typeof(result) === "function"){ | |
result = result() | |
} | |
return result; | |
} | |
return trampoline(factorial(1, num)); | |
} | |
factorial(1000000) //Uncaught RangeError: Maximum call stack size exceeded(…) | |
factorialSmart(1000000) //Infinity |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Helpful in understanding trampoline functions. One question. In the while loop while do
result &&
? In other words, it still works if I dowhile(typeof(result) === "function")
.