Home > Mobile >  How do I pass unspecified number of variables to Google Apps Script Custom Function
How do I pass unspecified number of variables to Google Apps Script Custom Function

Time:01-07

I have a Google Sheet. In this sheet, I want to run a custom function to do a complex calculation. This calculation will be based on values from other cells in other sheet tabs. For that reason, I want to be able to pass in a number of variables that is likely to change in the future.

I noticed the SUM function allows for optional parameters. The optional values are "repeatable". This is the behavior I want to reproduce in my custom function, repeatable/optional parameters. How does the SUM function allow for repeatable/optional parameters? How can I do the same in a custom function?

Thank you.

CodePudding user response:

You can use function rest parameter syntax:

function COMPLEXSUM(...args) {
  let sum = 0  

  args.forEach(x => {
    sum  = x
  })
  
  return sum
}

or if you want some parameters to be required and additionally some optional ones:

function COMPLEXSUM(param1, param2, ...args) {
  let sum = param1   param2
  
  return args.length === 0 ? sum : sum   args.reduce((pre, curr) => {
    return pre   curr;
  })
}
  •  Tags:  
  • Related