javascriptgoogle-apps-scriptwhile-loopgoogle-drive-api

Exiting While loop


I am using a helper function to search for a folder in Google Drive that contains a number. I want to search all folders and subfolders of a specific folder. The problem is that when it finds it it does not exit the while loop

function buscarCarpeta(origen, curso) {
  var curso = curso.toString();
  var folders = origen.getFolders();
  while (folders.hasNext()) {
    var folder = folders.next();
    var name = folder.getName();
    var scr = name.search(curso);
    if (scr > -1) {
      Logger.log("Encontrado");
      return folder
    }
    buscarCarpeta(folder, curso);
  }
}

I don't know how to do it so it returns the correct folder.


Solution

  • You don't stop the original while loop from continuing, even after the folder is found in a deeper level of the recursion.

    To fix this issue, you need to handle the result of the recursive call and break out when a match is found like this:

    function buscarCarpeta(origen, curso) {
        curso = curso.toString();
        var folders = origen.getFolders();
        
        while (folders.hasNext()) {
            var folder = folders.next();
            var name = folder.getName();
            var scr = name.search(curso);
            
            if (scr > -1) {
                Logger.log("Encontrado");
                return folder; // Exit on folder found
            }
            
            // Recursive call on subfolders
            var found = buscarCarpeta(folder, curso);
            if (found) {
                return found; // Return the folder
            }
        }
        
        return null; // no folder founded
    }
    

    Hope this was helpfull; happy coding!