How can I break/continue nested loops in Coffeescript? E.g. I have something like:
for cat in categories for job in jobs if condition do(this) ## Iterate to the next cat in the first loop
Also, is there a way to wrap the whole second loop as a conditional to another function within the first loop? E.g.
for cat in categories if conditionTerm == job for job in jobs do(this) ## Iterate to the next cat in the first loop do(that) ## Execute upon eliminating all possibilities in the second for loop, ## but don't if the 'if conditionTerm' was met
In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.
Most of times, instead of trying to look to another complex solutions such as caching and even more complex ones, understanding algorithms analysis can help us to write good and cheaper solutions. Moreover, in case the loops perform database queries using ORM, many nested loops can be improved by just using SQL JOINS.
The break statement, which is used to exit a loop early. A label can be used with a break to control the flow more precisely. A label is simply an identifier followed by a colon(:) that is applied to a statement or a block of code.
break
works just like js:
for cat in categories for job in jobs if condition do this break ## Iterate to the next cat in the first loop
Your second case is not very clear, but I assume you want this:
for cat in categories for job in jobs do this condition = job is 'something' do that unless condition
Use labels. Since CoffeeScript doesn't support them, you need to hack as such:
0 && dummy `CAT: //` for cat in categories for job in jobs if conditionTerm == job do this `continue CAT` ## Iterate to the next cat in the first loop do that ## Execute upon eliminating all possibilities in the second for loop, ## but don't if the 'if conditionTerm' was met
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With