The post I linked above shows a way to handle nested Array (in our analogy, nested boxes). Well, you know, it’s similar to a joke about gift box, which contains another box, and so on. Box-ception. Imagine if the Array above is changed to [1, , [3, []], ]]]. There is a box named Box A, which contains three things: number 1, Box B which contains number 2, and Box C which contains number 3 plus yet another Box D containing another Box E, which finally contains number 4.
That’s the code that the writer uses in the article. When I first saw it, I thought, “It shouldn’t be like this. It’s too complex, and not flexible”. Why I thought like that? Because the number of loops are defined explicitly. Imagine if we want to open a box-ception, we determine “how many nested boxes should we open”. That’s pretty much impossible to guess, isn’t it? Because we don’t know how many boxes inside boxes will there be. I agree with the way the writer uses using Array.prototype.reduce() from ECMAScript 6 (the one I said the newer and more compact way to handle nested arrays), but the code above, I really think it’s too complex and not flexible. What if the number of nested boxes is more than four? That code isn’t valid because the fifth and above box won’t be iterated/looked upon. I came up with another alternative.
Here’s the box-way. First, assume we don’t know if we want to open a box, therefore, we use Array.isArray() function to check if the thing we are going to see is a box or not. If that is a box, open that box and see what it contains. Then, apply the same method to each item inside that box. If that is not a box, then it is an item. Put it out (the return syntax).
I really think that in this life, we should always check if a solution is too complex or not. For example, if it is too complex, we may still be able to understand it, but another people (with expertise in the same domain) probably won’t. It will create a problem in the future, such as maintainability issue. Always seek alternatives of the current solution. When we think the current solution will be good enough FOREVER, we will see that time will chip away that solution slowly.