0

I have a tree object structured like this

function Node(){
    this.Info = "";
    this.Children = []; //Array of nodes
}

I have to validate the children under the parent. How do I do that using reflection? This is what I have so far.

function validChildren(node){
    if(!node.Children || node.Children.length == 0) return true;

    for(var child in node.Children){
        if(child.Children && child.Children.length > 0){
            if(!validChildren(child)) return false;
        }

        if(!validateChild(someParentObject, child.Info)) return false;
    }

    return true;
}

function validateChild(parent, info){
    //Assume this is implemented
}
user3587180
  • 1,317
  • 11
  • 23
  • `var this.Info = ""; var this.Children = [];` ?? are you sure this is not throwing error – NiRUS May 23 '17 at 03:57
  • @Nirus my actual implementation has those two properties but I the way data gets added to that function is little different. For brevity, I added that to show you guys how I'm implementing Tree structure. – user3587180 May 23 '17 at 04:01
  • Nirus's point is that those lines have syntax errors: you might want to [edit] the question to remove `var` from those lines so that it doesn't distract from what you're asking. – nnnnnn May 23 '17 at 04:11
  • @nnnnnn I fixed that. Thanks! – user3587180 May 23 '17 at 04:13
  • 2
    The "obvious" problem in the code you already have is that in the `for` loop where you call `validChildren(child)` you ignore its return value. if that function returns `false` because the `child`'s children failed validation then you need to `return false` immediately. – nnnnnn May 23 '17 at 04:15
  • @nnnnnn if you want to write it as an answer I'll accept it. Nice catch! – user3587180 May 23 '17 at 04:16
  • 1
    I don't have time now to check if that's the only problem, so that's why I just mentioned it in a comment instead of posting an answer. Another note: it seems a bit weird that the way you call the second function `validateChild()` implies that it returns `true` when the child is *not* valid - that seems backwards. – nnnnnn May 23 '17 at 04:18
  • [Don't use `for…in` enumerations on arrays!](https://stackoverflow.com/q/500504/1048572) – Bergi May 23 '17 at 06:02

0 Answers0