Please tell me the optimization of js recursion (the problem of tail recursion)

js tail recursive optimization

look at teacher Ruan Yifeng"s es6 tutorial, there is one thing I don"t understand when I"m recursive at the end

related codes

function tco(f) {
            var value;
            var active = false;
            var accumulated = [];
            return function accumulator() {
                accumulated.push(arguments);
                if (!active) {
                    active = true;
                    while (accumulated.length) {
                        value = f.apply(this, accumulated.shift());
                        console.log(value)
                    }
                    active = false;
                    return value;
                }
            };
        }

        var sum = tco(function (x, y) {
            if (y > 0) {
                return sum(x + 1, y - 1)
            } else {
                return x
            }
        });

        console.log(sum(1, 3))

ask why the variable value (not the last time) equals undefined

Jun.21,2021


value = f.apply(this, accumulated.shift());
...


function(x, y) {
      if (y > 0) {
            return sum(x + 1, y - 1)//undefined
       }
            ...
}

where f is the following function , and sum (x + 1, y-1) is undefined , if you want return value

    return function accumulator() {
        if (!active) {
            ...
        }
        return 'return data here'
    };

is blocked by active . When f is called recursively,

 

this article is too old, don't dwell on the problem.

although you can use the command line parameter -- harmony-tailcalls to enable tail recursive optimization in Node6 and Node7. However, this feature has been removed by V8, and the corresponding versions after Node8 have no tail recursive optimization feature.

Some versions of

before Chrome can indeed be opened via chrome://flags/-sharpenable-javascript-harmony , but they have also been removed.

because tail recursive optimization destroys the function's call stack information, TC39 is also looking for a new js syntax to explicitly indicate that tail recursive optimization is needed.

according to my test results just now, Firefox, Chrome and Node.js are not supported, and other engines are not tested. I guess they have also removed the support for tail recursive optimization.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e54cfd-2781b.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e54cfd-2781b.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?