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, Google+ or subscribe RSS

2 comments:



  1. This post is very useful for us. Because we have a lot of
    tips and tricks from this post. Thank you for this amazing post share. I many
    tips about < bd jobs as well. If you want to know more about a career sites, please visit our website.

    www.bd-career.com

    ReplyDelete
  2. You can be sure that you will only get the best online copy watch. Remember that buying fake watches is very similar to buying any other typeReplica watchesReplica Watches Uk

    ReplyDelete