Search code examples
javascriptrecursionstatic-members

Javascript: initializing a variable once (like a static variable) in a recursive function


I have a recursive function, which returns the leaf nodes of a tree (which is in the form of nested objects):

var retrieve = function (a)
{
    if (typeof retrieve.names == 'undefined') //would be true for the 1st pass only
        retrieve.names = []
    if (a.left != null)
        retrieve (a.left)
    if (a.right != null)
        retrieve (a.right)
    if (a.left == null && a.right == null)
        retrieve.names.push(a)
    return retrieve.names
}

The problem with this function is, it works perfectly fine for a single object (tree), but when another object is passed in the parameter, it simply appends the leaf nodes to the leaf nodes already obtained from the previous tree.

For instance,

// gets the leaf nodes of obj1 tree
obj1_leaves = retrieve(obj1) 

// instead of only getting leaf nodes of obj2, it appends them to leaf nodes of obj1
obj2_leaves = retrieve(obj2) 

Now the reason for this is typeof retrieve.names == 'undefined' is true only for first time. Whenever this function is invoked again, the member names of the retrieve function (which can also be considered as an object) is already set/initialized.

Is there a way to set a variable (or member of an object) inside a recursive function for a given function call only, and then unset/set it again for another function call.


Solution

  • You can use an inner function:

    function retrieve(a) {
      var names = [];
      function _retrieve(a) {
        if (a.left != null)
          _retrieve (a.left)
        if (a.right != null)
          _retrieve (a.right)
        if (a.left == null && a.right == null)
          names.push(a)
       }
       _retrieve(a);
       return names;
    }
    

    The outer function initializes the empty array as a local variable. The inner function does essentially the same work as your original function, but it references that local array.

    Every time retrieve() is called, a new local array is created and used to traverse the tree.