Tengo una clase para una calle que es solo una línea con un punto inicial y un punto final, dentro de esta misma clase tengo una función llamada checkIntersections que:
Decidí hacer de checkIntersections una función recursiva, pero creo que lo estoy haciendo mal porque no se detectan las intersecciones anidadas entre calles.
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]); } }}
¿Hay algo a lo que deba estar atento al hacer llamadas recursivas dentro de un bucle for en javascript? La salida de la función siempre está indefinida.
Su código no está utilizando el valor devuelto por la llamada recursiva, simplemente lo ignora y continúa con la siguiente llamada recursiva. En su lugar, debe detectar un éxito de una llamada recursiva y luego salir de inmediato, devolviendo ese éxito a su propia persona que llama.
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! } } }debería ser algo como
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 la llamada recursiva a checkIntersections.some para los children , ya que hará una salida anticipada