Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking/Continuing nested for loops in Coffeescript

Tags:

coffeescript

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 
like image 752
Engin Erdogan Avatar asked Oct 05 '11 01:10

Engin Erdogan


People also ask

Does continue break out of nested for loop?

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.

How do you stop a nested loop?

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.

How do I break out of nested loops in Javascript?

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.


2 Answers

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 
like image 144
Ricardo Tomasi Avatar answered Oct 20 '22 05:10

Ricardo Tomasi


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 
like image 40
matyr Avatar answered Oct 20 '22 05:10

matyr