Search code examples
javascriptrecursionappceleratorappcelerator-titanium

My recursive function not properly remove all children


This code remove all container's children, and set every children = null to free the memory. The structure of myElement is not always the same, so i would like a dynamic thing.

var cont1 = myElement.children.length;
for(var i = cont1 - 1 ; i >= 0 ; i--){
    var cont2 = myElement.children[i].children.length;
    for (var j = cont2 - 1; j >= 0; j--) {
        var cont3 = myElement.children[i].children[j].children.length;
        for (var k = cont3 - 1; k >= 0; k--) {
            var cont4 = myElement.children[i].children[j].children[k].children.length;
            for (var w = cont4 - 1; w >= 0; w--) {
                myElement.children[i].children[j].children[k].remove(myElement.children[i].children[j].children[k].children[w]);
                myElement.children[i].children[j].children[k].children[w] = null;
            }
            myElement.children[i].children[j].remove(myElement.children[i].children[j].children[k]);
            myElement.children[i].children[j].children[k] = null;
        }
        myElement.children[i].remove(myElement.children[i].children[j]);
        myElement.children[i].children[j] = null;
    }
    myElement.remove(myElement.children[i]); //i loop
    myElement.children[i] = null; //i loop
}

This is my recursive test function. Seems to work only in part. The first level is not deleted , it would be the i loop of the old code. How i can remove also that level of children?

function deleteRecursive(element){
    if(element.children.length > 0){
        for(var i = element.children.length - 1 ; i >= 0 ; i--){
            if(element.children[i].children.length > 0){
                deleteRecursive(element.children[i]);
            }else{
                element.remove(element.children[i]);
                element.children[i] = null;
            }
        }
    }
}

Solution

  • You should call remove also after you come back from the recursive call.

    NB: the first if is not necessary, as this condition is already checked by the for loop. And you can remove the similar check that you do before calling the function recursively, as again the recursive call will check it in its for loop:

    function deleteRecursive(element){
        for(var i = element.children.length - 1 ; i >= 0 ; i--){
            deleteRecursive(element.children[i]);
            element.remove(element.children[i]);
        }
    }