Data structures question! How would you find the *depth* of a particular string inside this array?
some result examples:
getDepth('block-1') => 0
getDepth('block-2') => 1
getDepth('block-4') => 2
How would you implement getDepth??
You’re iterating over the arrays multiple times, probably without realizing (icludes, and flat calls, besides the actual for loop). IMHO, the best you can do here is ether depth-first or breadth-first traversal, so you can find your element in O(n) in the worst case.
the thing is that every element is an array!, inside each element if could be either just one string (id) or string + another array (children)
trying to code your pseudo-code!, will let you know the result.
Recursion is often not the most performant solution, but I’ll take the simplicty, elegance and declarativeness of it over performance any time, unless facing actual proof that performance of the code is impacting the app.
... I never think about it unless facing it and 100% sure that the code I am looking at is the culprit. Most times, with performance issues, I always find the problem to be somewhere else, intuition is deceptive ;)