Is it a tail? (Javascript)

Suppose you have a recursive function, for example:

Blah.prototype.add = function(n) { this.total += n; this.children.forEach(function(child) { child.add(n); }); }; 

Is the tail call child.add() ? If not, can it be written like this?

+6
source share
2 answers

Yes, this is a tail call:

 function(child) { child.add(n); // ^ tail } 

However, there is no tail recursion here because it is not a direct recursive call.

Also this.children.forEach(…) is the tail call in the add method.

However, the callback call inside the built-in forEach method is probably not optimized for the callback (and all but the last cannot be anyway). You can make it rewrite its function to

 Blah.prototype.add = function(n) { "use strict"; this.total += n; let l = this.children.length; if (!l--) return; for (let i=0; i<l; i++) this.children[i].add(n); this.children[i].add(n); // tail-recursion }; 

Note that none of these tail calls will be optimized unless you also achieve return results.

+1
source
+1
source

Source: https://habr.com/ru/post/988809/


All Articles