Were there `do ... while` loops left without CoffeeScript ...?

In CoffeeScript, the while comes standard:

 while x() y() 

However, the following 1 does not work:

 do y() while x() 

And this is just sugar for the first example:

 y() while x() 

Does CoffeeScript have a built-in loop that runs at least once?

1 As an alternative, do is a keyword - it is used to call anonymous functions.

+52
coffeescript
May 19 '11 at 1:49
source share
5 answers

The CoffeeScript documentation says:

The only low-level loop that CoffeeScript provides is the while loop.

I don’t know about the built-in loop that runs at least once, so I guess the alternative

 loop y() break if x() 
+63
May 19 '11 at 2:22
source share

I know this answer is very old, but since I entered here through Google, I thought that someone else could do it.

To build a do ... while loop equivalent in CoffeeScript, I think this syntax emulates it to be the best and easiest and very readable:

 while true # actions here break unless # conditions here 
+24
Jun 20 '13 at 8:24
source share

Your guess is correct: there is no do-while equivalent in CoffeeScript. Therefore you usually write

 y() y() while x() 

If you do this often, you can define a helper function:

 doWhile = (func, condition) -> func() func() while condition() 
+16
May 19 '11 at 4:49
source share

I found that this can be accomplished with a short circuit:

 flag = y() while not flag? or x() 
+1
Jul 18 '13 at 2:10
source share

I am working on a project in which I just make the condition evaluate at the end of the loop and then finish at the beginning.

 # set the 'do' variable to pass the first time do = true while do # run your intended code x() # evaluate condition at the end of # the while code block do = condition # continue code 

It is not very elegant, but it does not allow you to define a new function only for your block of code and run it twice. There is usually a way to encode do ... while instructions, but for those cases where you cannot have a simple solution.

0
Feb 27 '13 at 19:53
source share



All Articles