Join three functions in one (one file)

Asked

Viewed 98 times

-1

I have three independent functions, which perform separate tasks. I would like to combine these three functions into one, but to do the same thing that the three of you do independently. How can I do that? NOTE: The three functions are working, without any error. I really only need to join them in one. The last function takes an argument, event, and executes when a row in the table is changed. The first two functions perform every minute(googledocs Trigger)

Function 1: Hide rows from a googledocs table

function escondeLinhas() {
var sheet = SpreadsheetApp.getActive().getSheetByName("AlertaCompleto"); //Altere o nome da aba
var lastRow=sheet.getLastRow();
var arr=sheet.getRange(1,11,lastRow,1).getValues(); //Substitua o 3 pelo nº da coluna onde se encontra a string a ser pesquisada
    for(var i=0;i<arr.length;i++) {
        if(arr[i][0]=="Concluido no Prazo" || arr[i][0]=="Concluido Fora do Prazo") {
         sheet.hideRows(i+1);  //ESCONDE A LINHA
      }
    }
}

Function 2: Generates a URL of a cell address in googledocs

    function geraURL() {
    var spreadsheet = SpreadsheetApp.getActive().getSheetByName('AlertaCompleto');
     //  var data = new Date();
    //   data = Utilities.formatDate(data, "GMT-03:00","dd-MM-yyyy' 'HH:mm:ss' '"); verificar possibilidade de inserir data de atualização de informações automaticamente

      for (var i=2; i<1000;i++) {
        if (spreadsheet.getRange('C'+i).getValue()!= "") {//Se coluna C contiver algum valor, gerar URL na coluna L
            spreadsheet.getRange('L'+i).activate();
            spreadsheet.getCurrentCell().setValue('https://docs.google.com/spreadsheets/d/11RyO150lEMkDB/edit#gid=1131&range='+i+':'+i);
            //spreadsheet.getRange("I"+i).setValue(data); //Erro. Atualiza ate a linha 9

            spreadsheet.getRange('A'+i+':'+'K'+i).activate(); //aplica borda
            spreadsheet.getActiveRangeList().setBorder(true, true, true, true, true, true, '#000000', SpreadsheetApp.BorderStyle.SOLID)
            .setBorder(true, true, true, true, true, true, '#000000', SpreadsheetApp.BorderStyle.SOLID_MEDIUM);

      }
    }
}

Function 3: Update date in a googledocs cell

function onEdit(event) {
 var ActiveSheet= SpreadsheetApp.getActiveSheet();
   var capture = ActiveSheet.getActiveCell();
   if(capture.getColumn() == 9 || capture.getColumn() == 10 && ActiveSheet.getName() == "AlertaCompleto" ){
     var add = capture.offset(0,4);
       var data = new Date();
       data = Utilities.formatDate(data, "GMT-03:00","dd-MM-yyyy' 'HH:mm:ss' '");
       add.setValue(data);
   }
}

1 answer

1


I do not recommend doing this. Do not aggregate your functions into one. Let them be diluted as they are, after all, the functions have the function (Pun intended!) to compartmentalize code into simpler tasks to make code changes and maintenance easy.

I also don’t recommend creating global variables for repetitive codes, instead, "pack" (wrap) your code. Study some JS architectures and choose the one that best suits your problem.

In the simple case presented here, I would recommend a Singleton, which is generically the most used. This shows its simplicity and effectiveness in containing the Hoisting and create an organized and easy-to-maintain code, which is undoubtedly an excellent thing.

You create an object:

var googSpreadSheet = (function() {

    let sheet = SpreadsheetApp.getActive().getSheetByName("AlertaCompleto");

    return {
        escondeLinhas: function() {
            var lastRow = this.sheet.getLastRow();
            var arr = this.sheet.getRange(1, 11, lastRow, 1).getValues(); //Substitua o 3 pelo nº da coluna onde se encontra a string a ser pesquisada
            for (var i = 0; i < arr.length; i++) {
                if (arr[i][0] == "Concluido no Prazo" || arr[i][0] == "Concluido Fora do Prazo") {
                    this.sheet.hideRows(i + 1); //ESCONDE A LINHA
                }
            }
        },

        geraURL: function() {
            for (var i = 2; i < 1000; i++) {
                if (spreadsheet.getRange('C' + i).getValue() != "") { //Se coluna C contiver algum valor, gerar URL na coluna L
                    spreadsheet.getRange('L' + i).activate();
                    spreadsheet.getCurrentCell().setValue('https://docs.google.com/spreadsheets/d/11RyO150lEMkDB/edit#gid=1131&range=' + i + ':' + i);
                    spreadsheet.getRange('A' + i + ':' + 'K' + i).activate(); //aplica borda
                    spreadsheet.getActiveRangeList().setBorder(true, true, true, true, true, true, '#000000', SpreadsheetApp.BorderStyle.SOLID)
                        .setBorder(true, true, true, true, true, true, '#000000', SpreadsheetApp.BorderStyle.SOLID_MEDIUM);

                }
            }
        },

        onEdit: function(event) {
            var ActiveSheet = SpreadsheetApp.getActiveSheet();
            var capture = ActiveSheet.getActiveCell();
            if (capture.getColumn() == 9 || capture.getColumn() == 10 && ActiveSheet.getName() == "AlertaCompleto") {
                var add = capture.offset(0, 4);
                var data = new Date();
                data = Utilities.formatDate(data, "GMT-03:00", "dd-MM-yyyy' 'HH:mm:ss' '");
                add.setValue(data);
            }
        }
    };
}());

Of course, in this example, which should not be used in production, you have a very basic example, with all methods being public.

You can access the methods like this:

// Supondo que você clique num botão com ID "esconde-linhas"
// para executar o método googSpreadSheet.escondeLinhas(), sem parâmetros

var buttonEscondeLinhas = document.getElementById("esconde-linhas");

buttonEscondeLinhas.addEventListener("click", googSpreadSheet.escondeLinhas()); 


Take a look at Javascript Design Patterns.

  • 1

    I took the liberty of editing and removing the final section, because although it is a relevant discussion (how the site works and how it should work, etc.) it has no relation to the question. Make yourself at home :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.