title: Optimize Google Apps Script That Searches a Column for Matching Multiple Substrings
body: <p>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.</p>
  
  <pre><code>function allNames(setOfStrings, mainString){
    var i = 0;
    var bool = "true";
    while(i &lt; setOfStrings.length &amp;&amp; bool == "true"){
      var indexCheck = mainString.indexOf(setOfStrings[i]);
      if(indexCheck &gt; -1){
      var bool = "true";
      }
      else{
      var bool = "false";
      }
      i++;
   }
    return bool;
  }
  </code></pre>
  
  <p>Checks the string and returns true if all substrings are contained within it</p>
  
  <pre><code>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 &lt; 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)
      }
  </code></pre>
  
  <p>If true is returned from first function this prints it in the next empty cell of a specific range.</p>
  
  <p>Any help would be greatly appreciated.</p>