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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With