1

I have the following function taken from (Iterate through Nested JavaScript Objects) implemented in a plain CRNA project:

var findObjectByLabel = function(obj, label) { if(obj.label === label) { return obj; } for(var i in obj) { if(obj.hasOwnProperty(i)){ var foundLabel = findObjectByLabel(obj[i], label); if(foundLabel) { return foundLabel; } } } return null; };

When i try to execute this code in the constructor or any lifecycle method, the app crashes with Maximum Call Stack Size exceeded. Is this something that is not allowed in RN? Will I have to convert this into an iterative version?

Android Noob
  • 3,271
  • 4
  • 34
  • 60

1 Answers1

1

If you consider the following scenario for your above function, you can see why it is breaking:

type Node = { link: Node; value: number; };
const x: Node = { link: null, value: 0 };
const y: Node = { link: x, value: 1 };
x.link = y;

findObjectByLabel(x, 'foo');

Because there is a circular reference, your recursion is going to go on infinitely and you will hit the max call stack size.

It is likely that there is some sort of circular reference within your object structure that is running you up against this problem.

If you can guarantee that all hit objects will have a non-null label and that labels are unique you could keep track of seenLabels and not recursive into an object that you've already seen the label of.

casieber
  • 7,264
  • 2
  • 20
  • 34