Recursive stack overflow and solutions in JavaScript

Source: Internet
Author: User

On the stack overflow problem, in the daily development of JavaScript is very common, Google, the related issues are more. This article is intended to describe how to resolve this type of problem. First look at an example (of course you can do it in an easier way, here we only discuss recursion):

function IsEven (num) {    if (num = = 0) {        return true;    }    if (num = = 1) {        return false;    }    Return IsEven (Math.Abs (num)-2);} Outputs:trueconsole.log (IsEven),//outputs:falseconsole.log (IsEven (9));

When we change the parameter to 10000, a stack overflow occurs during the run of the following meeting:

function IsEven (num) {    if (num = = 0) {        return true;    }    if (num = = 1) {        return false;    }    Return IsEven (Math.Abs (num)-2);} Different JavaScript engine error may differ//outputs:uncaught rangeerror:maximum call stack size exceeded Console.log (IsEven (10000));

The reason is that each time code execution, will be allocated a certain size of the stack space (1M in the Windows system), each method call will be stored in the stack of information (such as parameters, local variables, return values, etc.), the information will also occupy a certain amount of space, thousands of such spaces accumulate, Nature is more than the thread of the stack space. So how to solve this kind of problem?

Using closures:
function IsEven (num) {    if (num = = 0) {        return true;    }    if (num = = 1) {        return false;    }    return function () {        return IsEven (Math.Abs (num)-2);}    } Outputs:trueconsole.log (IsEven (4) () ());

At this point, an anonymous function is returned each time it is called, and the associated parameters and local variables of the anonymous function execution are freed without additional stack size.

Optimization Call:

The above example call is more cumbersome and optimized as follows:

function IsEven (num) {    if (num = = 0) {        return true;    }    if (num = = 1) {        return false;    }    return function () {        return IsEven (Math.Abs (num)-2);}    } function Trampoline (func, arg) {    var value = func (arg);    while (typeof value = = = "function") {        value = value ();    }    return value;} Outputs:trueconsole.log (Trampoline (IsEven, 10000));//outputs:falseconsole.log (Trampoline (IsEven, 10001));

Now we can solve the stack overflow problem, but it is not felt every time Tarmpoline (IsEven, 1000) This call method is not very good, we can use bind to bind:

function IsEven (n) {    /**     * [iseveninner recursion]     * @param  {[type]}  num [description]     * @return { Boolean}     [description]     */    function Iseveninner (n) {        if (n = = 0) {            return true;        }        if (n = = 1) {            return false;        }        return function () {            return Iseveninner (Math.Abs (n)-2);        }    }    /**     * [Trampoline iteration]     * @param  {[Type]} func [description]     * @param  {[type]} arg  [ Description]     * @return {[type]}      [description]     *    /function Trampoline (func, arg) {        var value = func (arg);        while (typeof value = = = "function") {            value = value ();        }        return value;    }    return Trampoline.bind (NULL, Iseveninner) (n);} Outputs:trueconsole.log (IsEven (10000));//outputs:falseconsole.log (IsEven (10001));

Although the above example achieves the desired effect, the trampoline function has some limitations:

1. Suppose you pass only one parameter to the recursive function

Value = func (ARG); Modified to Value = Func.apply (func, Arg);

2. Assuming that the last return value is not a function of the implementation of a more robust, see the source code in Underscore-contrib.

Thank you for your reading, the text of the inappropriate point also hope that the criticism, the article has been synchronized to a personal blog if you have good suggestions, welcome to leave a message, the DA!

Reprint statement:

This article title: Recursive stack Overflow and solution in JavaScript

This article link: http://www.zuojj.com/archives/1115.html, reprint please specify transfer from benjamin-focus on front-end development and user experience

Recursive stack overflow and solutions in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.