My apologies to everyone for previous versions of this being vague. Someone has decided to have pity on the new girl and help me rewrite this question - here\'s an update that
One possible optimization of recursion is to evaluate lazily, that is, return a "computation" (=function) that will return a value instead of computing and returning it straight away.
Consider a function that sums up numbers (in a rather silly way):
function sum(n) {
return n == 0 ? 0 : n + sum(n - 1)
}
If you call it with n = 100000
it will exceed the stack (at least, in my Chrome). To apply the said optimization, first convert it to true tail-recursive, so that the function returns just a call to itself and nothing more:
function sum(n, acc) {
return n == 0 ? acc : sum(n - 1, acc + n)
}
and wrap this direct self-call with a "lazy" function:
function sum(n, acc) {
return n == 0 ? acc : function() { return sum(n - 1, acc + n) }
}
Now, to obtain the result from this, we repeat the computation until it returns a non-function:
f = sum(100000, 0)
while(typeof f == "function")
f = f()
This version has no problems with n = 100000, 1000000 etc