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 :
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.
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!
}
}
}
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;
}
return the recursive call to checkIntersections.some for the children as it will do a early exit