Skip to content

Instantly share code, notes, and snippets.

@junjchen
Last active October 8, 2018 06:39
Show Gist options
  • Save junjchen/86b0b8bbd20e17b3f3b5491fbaa7d1f9 to your computer and use it in GitHub Desktop.
Save junjchen/86b0b8bbd20e17b3f3b5491fbaa7d1f9 to your computer and use it in GitHub Desktop.
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
Copy link

ghost commented Oct 8, 2018

Helpful in understanding trampoline functions. One question. In the while loop while do result &&? In other words, it still works if I do while(typeof(result) === "function").

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment