Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsmap-function

Map() function with inner function or nested Ternary Operator best practices Google script


I have two methods of writing the same function using Map(), from my reading I can not tell if there is a best practices method

Related to this are nested ternary operations considered bad practice?

Method2

function Method2() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();  
  var sht = ss.getSheetByName('Elements');  
  var rng = sht.getDataRange();
  var values = rng.getValues();
  
  values = values.map(x => x.map(y => giveNumber(y)));
  
  sht.getRange(1,1, values.length, values[0].length).setValues(values);
}


function giveNumber(str) {  
  if(str=="Networking - 1") {str=1}
  else if(str=="Cooperating - 2") {str=2}
  else if (str=="Collaborating - 3"){str=3}
  else if(str=="Partnering - 4") {str=4}
  else {str=str}
  return str
}

Method3

function Method3() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();  
  var sht = ss.getSheetByName('Elements');  
  var rng = sht.getDataRange();
  var values = rng.getValues();
  
  values = values.map(x => x.map(y => y==("Networking - 1") ? 1: 
                                      y==("Cooperating - 2") ? 2: 
                                      y==("Collaborating - 3") ? 3: 
                                      y==("Partnering - 4") ? 4: 
                                      y));
  
  
  sht.getRange(1,1, values.length, values[0].length).setValues(values);
}


Solution

  • When you have multiple conditions to check, ternary operators can not be used efficiently.

    It is recommended to use an if/else if statement:

    values = values.map(x => x.map(y =>
                        {
                        if (y== "Networking - 1"){
                        return 1;
                        }
                        else if(y=="Cooperating - 2"){
                        return 2;
                        }
                        else if(y=="Collaborating - 3"){
                        return 3;
                        }
                        else {
                        return 4;                     
                        }                
                        }
     ));