Sunday, April 5, 2015

Recursion in Google Apps Script

The recursion is very usefull and probably first hard-to-understand-knowledge for new programmers. It is usefull when you want to to call the same function again and again, but with different values as a parameter.

Well know example is calculating factorial. Factorial of 5, contains factorial  4 and its contains factorial of 3 etc.

...
5! = 5 * 4! = 5 * 4 * 3! = 5 * 4 * 3 * 1 = 120
4! = 4 * 3! = 4 * 3 * 2! = 4 * 3 * 2 * 1 = 24
...

So you can write function like

function factorial(n) {
  if (n == 0 || n == 1) return 1;
  if (f[n] > 0)  return f[n];
  return f[n] = n * factorial(n-1);  
} ​
If you run factorial(5), it will call function 5 time. Every new calling will inserted into another.

There is small limitation in Google Apps Script during recursion. You can call only 1000 inherited functions.
If your script call multiple times, you will get error:
Exceeded maximum stack depth 

Are you interested in this topic? Follow me on Twitter or subscribe RSS