Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect infinite recursion?

Lets assume I have a function that crawls over an array...

flatten([a, b, c, d, [e, f, g, [h, i, j, k], l], m, n, o, p])
>> [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p]

Flatten would crawl over the code and for each array encountered would recursively enter into that array and return the values such that you have a flat array.

This works until we have an array such as:

a    = [];
a[0] = a;

This obviously creates infinite recursion:

Array[1]
0: Array[1]
 0: Array[1]
  0: Array[1]
   0: Array[1]
    0: Array[1]
     0: Array[1]
      ...

How can I detect this behavior without modifiying the array such that the function can deal with this?

like image 236
Incognito Avatar asked Mar 08 '12 15:03

Incognito


1 Answers

If detecting recursion is a requirement, you're going to have to trade memory space for it: create an array of objects you parsed (the parameters you send recursively) and check each new parameter against it. If you already parsed it, return immediately.

like image 91
Blindy Avatar answered Sep 30 '22 15:09

Blindy