3

I've read the dozen variations on this question, but those answers haven't led me to what must be an obvious mistake. Why does this always return false? Why do I see called again even after a found it? And if I put a return in front of the recursive call, why do I never see found it?

function subResult (object, start, target){
    console.log('called again')
    if (start === target){
      console.log('found it')
      return true
    } else {
      for (var i = 0; i < object[start].edges.length; i++){
        subResult(object, object[start].edges[i], target)
      }
    }
   return false
 }

1 Answer 1

4

Change

for (var i = 0; i < object[start].edges.length; i++){
    subResult(object, object[start].edges[i], target)
}

to

for (var i = 0; i < object[start].edges.length; i++){
    if (subResult(object, object[start].edges[i], target)) {
       return true;
    }
}

I.e. when found your done. If not keep going.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that was it. Thanks so much. So I'm saying something like "if the recursive call returns true, return true"? I really thought it would be sufficient to do the first return true and then return the recursive call (as in Abu Hanifa's answer) but that just resulted in false always being returned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.