See the following pseudocode snippet that approximates my situation:
function foo () {
for ( velocity=0; velocity<100; velocity++ ) {
root1 = computeRoot1();
root2 = computeRoot2();
// do a bunch of computation with root1
// if result of computation is undesirable, do computations again with root2
}
So, basically I want to do the computations in the body of the for loop with root1, and then root2 if root1‘s computation result is invalid.
My first instinct was the obvious approach, to wrap the computation in a help function, but I’m not sure this is the most clear approach. I’m trying for good collocation of information in my code, and a function call for code that will be executed at most twice (per iteration) defeats that goal without providing a great deal of conciseness to my code.
I was thinking perhaps a for loop like:
for ( root=root1; root1IsInvalid==true || bothRootsInvalid==true; root=root2 )
or a while with similar functionality. But I’m certainly open to other suggestions
As someone reading this code, which approach would make it the most readable and concise to you?
As an aside, I’m writing this particular function in JavaScript, but language-agnostic solutions would be awesome.
EDIT: clarified code snippet
You have several basic approaches:
forloop to run the same code on each item in the array, perhaps stopping the iterations when some condition is met.whileloop and repeat your code until some condition is met.The first option is easier to extend to N items. The second option is perhaps simpler for just two items.
You can make the computation function be a local function (declared and used inside the function you are currently executing) so it doesn’t add to the global namespace and your code remains more encapsulated.
I’m also not sure what you intend to be doing with this line:
But, it is only assigning the value to
root2and it looks like you probably wantvarin front of these to define them as local variables.