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.
Just iterate over the input array, if element is string check if it’s the one you look for, if it’s an array, recursively call getDepth for this array, continue until you found the element.
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.
thanks!!
solved!! I needed to tweak a little bit the implementation but I guess this one is more performant?
here's the code if you want to play with it (open the console)
codesandbox.io/s/broken-paper…
I was looking to see if there was a solution using lodash, was hoping there was a way to return the dot notation path of a match so you could just count the dots 😂
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.
solved!! I needed to tweak a little bit the implementation but I guess this one is more performant?
here's the code if you want to play with it (open the console)
codesandbox.io/s/broken-paper…
Due to the usage of recursion, this one is readable and much easier to understand what it is doing. Performance? I am pretty sure that if we ditch recursion we can make it more performant, but..
... 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 ;)