How can I write a for loop with multiple conditions?
Intended Javascript:
for(k=1; k < 120 && myThing.someValue > 1234; k++){
myThing.action();
}
js2coffee.org indicates that I should use a while loop:
k = 1
while k < 120 and myThing.someValue > 1234
myThing.action()
k++
but this ends up compiling back to a while loop in javascript.
Is there a way to write coffescript to compile to my intended javascript and include extra conditions in the for loop itself?
If the answer to that question is false, then what would be the nicest way to get the same functionality with coffeescript?
My best while loop solution so far is
k = 1
myThing.action() while k++ < 120 and myThing.someValue > 1234
Since a for
loop is equivalent to a while
loop plus a couple of statements, and CoffeeScript offers only one kind of for
loop, use a while
loop. If you’re trying to get specific JavaScript output, you should probably not be using CoffeeScript.
Of course, there is always
`for(k=1; k < 120 && myThing.someValue > 1234; k++) {`
do myThing.action
`}`
Avoid.
Trying to write CoffeeScript that produces specific JavaScript is a bit silly and pointless so don't do that.
Instead, translate the code's intent to CoffeeScript. You could say:
for k in [1...120]
break if(myThing.someValue <= 1234)
myThing.action()
And if you're not actually using the loop index for anything, leave it out:
for [1...120]
break if(myThing.someValue <= 1234)
myThing.action()
Both of those produce JavaScript that is structured like this:
for(k = 1; k < 120; k++) {
if(myThing.someValue <= 1234)
break;
myThing.action();
}
That should have the same effect as your loop. Furthermore, I tend to think that those three loops are more maintainable than your original as they don't hide the exceptional condition inside the loop condition, they put it right in your face so you can't miss it; this is, of course, just my opinion.