Home > Net >  recursive function that calls recursion inside for loop in javascript
recursive function that calls recursion inside for loop in javascript

Time:01-01

I have a class for a Street which is just a line with a beginning point and an end point, inside this same class I have a function called checkIntersections which :

  • checks if this Street intersects with a given Street and its children which are also of type Street.
  • returns true at the first found intersection
  • returns false or undefined if no recursive intersections were found

I decided to make checkIntersections a recursive function but I think I'm going about it wrong because nested intersections between streets are not being detected.

  checkIntersections(street){

if(intersects(this.beginning, this.end, street.beginning, street.end)){
  return true;
}
else{
  for(var i = 0 , count = street.children.length ; i < count ; i  ){
    this.checkIntersections(street.children[i]);  
  }
}

}

Is there anything that I should be attentive to while making recursive calls inside a for loop in javascript ? The output of the function is always undefined.

CodePudding user response:

Your code is not using the value returned from the recursive call -- it just ignores it and just continues with the next recursive call. Instead it should detect a success from a recursive call and then exit immediately, returning that success to its own caller.

checkIntersections(street) {
    if (intersects(this.beginning, this.end, street.beginning, street.end)) {
        return true;
    } else {
        for (let child of street.children) { // Use modern for..of loop
            let success = this.checkIntersections(child);
            if (success) return true; // bubble up the happy result!
        }
    }
}

CodePudding user response:

It should be something like

checkIntersections(street) {
  if (intersects(this.beginning, this.end, street.beginning, street.end)) {
    return true;
  } else if (street.children.length) {
    return street.children.some( checkIntersections );
  }
  return false;
}

  • you need to return the recursive call to checkIntersections
  • it would be better to use .some for the children as it will do a early exit
  • you need to provide a default return in case there are no children and the current intersection failed.
  • Related