'Creating an Apps Script function that takes other functions as arguments

I want to create a function in APPSCRIPT that takes as argument another APPSCRIPT function.

I tried this:

function mainFunction(spreadsheetRange, secondaryFunction) {
  
  // values = array of values retrieved from range
  for (var i = 0; i < values.length; i = i+1) {
    values[i] = secondaryFunction(values[i]);
  }

  // update the range with the new values
}


function function1() {
  //something
}

function function2() {
  //something
}

and running (after importing all these functions) in a google sheet cell the following formula: =mainFunction(validrange, function2)

But this error appears: TypeError: fun is not a function.

The same happens with=mainFunction(validrange, function2())

How can I solve this problem?



Solution 1:[1]

Although I'm not sure whether I could correctly understand your goal, the following modified script is your expected result?

Modified script:

function mainFunction(spreadsheetRange, secondaryFunction) {
  
  // values = array of values retrieved from range
  for (var i = 0; i < values.length; i = i+1) {
    values[i] = this[secondaryFunction](values[i]); // <--- Modified
  }

  // update the range with the new values
}
  • In this modification, for example, when you put =mainFunction(validrange, "function2") to a cell, the function function2 is used with values[i] = this[secondaryFunction](values[i]).

    • But when I saw your function of function2, no arguments are used. So, in this case, values[i] is not given to function2. Please be careful about this.
  • In this case, please use "function2" of =mainFunction(validrange, "function2") as the text value. Please be careful about this.

Solution 2:[2]

I see no problem to pass a function as an argument:

function main() {

  function mainFunction(func, arg) {
      return func(arg);
  }

  function function1(num) { return num * 2 }

  function function2(num) { return num * 3 }

  var value = mainFunction(function1, 2);
  console.log(value) // output ---> 4

  var value = mainFunction(function2, 2);
  console.log(value) // output ---> 6

}

You can try it right here:

function mainFunction(func, arg) {
    return func(arg);
}

function function1(num) { return num * 2 }

function function2(num) { return num * 3 }

var value = mainFunction(function1, 2);
console.log(value) // output 4

var value = mainFunction(function2, 2);
console.log(value) // output 6

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tanaike
Solution 2