Supose you have a recursive function like:
Blah.prototype.add = function(n) {
this.total += n;
this.children.forEach(function(child) {
child.add(n);
});
};
Is the child.add()
a tail call? If not can it be written so it is?
Supose you have a recursive function like:
Blah.prototype.add = function(n) {
this.total += n;
this.children.forEach(function(child) {
child.add(n);
});
};
Is the child.add()
a tail call? If not can it be written so it is?
Are any Javascript engines tail call optimized?
JavaScript as it is currently will not optimise for that
Another option would be a trampoline https://taylodl.wordpress.com/2013/06/07/functional-javascript-tail-call-optimization-and-trampolines/
Yes, it is a tail call:
Yet nothing here is tail-recursive, because it's not a direct recursive call.
Also
this.children.forEach(…)
is a tail call within theadd
method.However, the invocation of the callback within the native
forEach
method is probably not tail-call optimised (and all but the last one cannot be anyway). You can force it by rewriting your function toNotice that none of these tail calls will be optimised if you don't also
return
their results.