0

I recently wrote some Google Apps scripts code that searches each cell in a column to check for multiple substrings in one main string. Unfortunately there are about 21000 main strings that it has to search through which takes so long that it sometimes times out. I'm not an experienced programmer so I was wondering if I was using best practices when writing this code, or if there's a way that I can optimize it.

function allNames(setOfStrings, mainString){
  var i = 0;
  var bool = "true";
  while(i < setOfStrings.length && bool == "true"){
    var indexCheck = mainString.indexOf(setOfStrings[i]);
    if(indexCheck > -1){
    var bool = "true";
    }
    else{
    var bool = "false";
    }
    i++;
 }
  return bool;
}

Checks the string and returns true if all substrings are contained within it

function previewPlacements(){
      var ss = SpreadsheetApp.openById("1f1vGK88OeUcfAEVQ0R06LLa8iq1- 
    99_KFyaxsyU4aRs");
      var add = ss.getSheetByName("Add Placements");
      var ps = ss.getSheetByName("Placement Import");
      var rowNum = 2;  
      var codes = add.getRange(["E1:G1"]).getValues().join().split(',');
      var plCountCell = ps.getRange("I1").getValue();
      var contains = "";
      for(i = 0; i < 4000; i++){
        var ct = getFirstEmptyRowPlacement();
        var placement = ps.getRange(rowNum + i, 1).getValue();
        var addRange = add.getRange(ct + 10, 3);
        var contains = allNames(codes, placement);
        if(contains == "true") {addRange.setValue(placement);                      
                       }
      }
      Logger.log(plCountCell)
    }

If true is returned from first function this prints it in the next empty cell of a specific range.

Any help would be greatly appreciated.

Nick
  • 9
  • 1
  • Possible duplicate of [Google app script timeout ~ 5 minutes?](https://stackoverflow.com/questions/14450819/google-app-script-timeout-5-minutes) – TheMaster Dec 18 '18 at 00:17

1 Answers1

0

Try these:

function allNames(setOfStrings,mainString){
  var rv=true;
  for(var i=0;i<setOfStrings.length;i++){
    if(mainString.indexOf(setOfStrings[i])==-1){
      rv=false;
      break;
    }
  }
  return rv;
}

function previewPlacements(){
  var ss=SpreadsheetApp.openById("1f1vGK88OeUcfAEVQ0R06LLa8iq1-99_KFyaxsyU4aRs");
  var add=ss.getSheetByName("Add Placements");
  var ps=ss.getSheetByName("Placement Import");
  var rowNum=2;  
  var codes=add.getRange(["E1:G1"]).getValues()[0];
  var plCountCell=ps.getRange("I1").getValue();
  for(var i=0;i<4000;i++){//Why 4000?
    var ct=getFirstEmptyRowPlacement();
    var placement=ps.getRange(rowNum + i, 1).getValue();
    var addRange=add.getRange(ct + 10, 3);
    var contains=allNames(codes, placement);
    if(contains==true){addRange.setValue(placement);}
  }
}
Cooper
  • 59,616
  • 6
  • 23
  • 54