Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The correct return value is getting lost in the chain of recursive function calls. After the correct value is found, any additional searches made will return incorrect values from that point on.</p> <p>A couple ways to handle this:</p> <p><strong>1&#x2E; Cancel the search</strong></p> <p>When the correct value is found, immediately return it all the way up the recursive stack, without searching any more of the current arrays or the nested arrays. In other words, cancel the rest of the search.</p> <p>@Barmer's answer is an example of this. The key part of his code is the use of <code>for</code> loops rather than the <code>each</code> method to iterate through the arrays, since it's much easier to interrupt a <code>for</code> loop.</p> <p><strong>2&#x2E; Store the value somewhere safe</strong></p> <p>When the correct value is found, store it somewhere safe, allow the rest of the search to continue, and after the initial function call has finished access the value. The simplest way is to store the correct value in a global variable, though that's not a good practice as it violates the encapsulation of the function.</p> <p>@shyam's answer presents a cleaner solution: Passing a reference to a global variable as a function parameter, setting the parameter when the correct value is found, and then accessing the global variable after the initial function call has finished.</p> <p><strong>Choosing between the two</strong></p> <p>In laymen's terms, the intended logic of the function could be summed up as follows: When you find what you're looking for, stop, and let me know what it is immediately. The only reason to continue searching would be if multiple pieces of data needed to be found. I'm assuming that's not the case here.</p> <p>Of the two approaches, &#x23;2 is a quick-fix workaround that should work fine but will further confuse anyone who's trying to understand the intended logic of the function. Why is the search continuing if it's only looking for a single piece of data that's already been found?</p> <p>&#x23;1 is a refactoring of the function so that it behaves more consistently with the intended logic, which would make the function easier to understand. The function stops searching when it finds what it needs.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload