yz10
yz10

Reputation: 731

Converting a while loop to a for loop in Coffeescript

It seems like a simple conversion, but I can't seem to find the syntax for it.

i = start
while(if step > 0 then i < end else i > end)
  array.push i
  i += step

start, end, and step are a signed integers

Upvotes: 1

Views: 353

Answers (2)

Mark Reed
Mark Reed

Reputation: 95252

You should read the CofeeScript page on loops. But the way to do this in CoffeeScript is with a list comprehension iterating over a range:

(array.push i for i in [start...end] by step)

But note that a list comprehension returns a value. For instance, given this code:

start = 10
end = 5
step = -2
array = []
(array.push i for i in [start...end] by step)

The variable array winds up with the value [10,8,6], as expected, but since push returns the new length of the array it just pushed onto, the return value of that last statement - which will be returned if it's the last thing in a function, or printed if you enter the above at the REPL, etc. - is [1, 2, 3].

EDIT So it would be better, as noted below, to just construct the array with the list comprehension in the first place:

array = (i for i in [start...end] by step)

When building a range, note that ... yields an exclusive range in terms of the right endpoint, while .. yields an inclusive one. So [1..5] includes 5 in the list, while [1...5] stops at 4.

Also, if you really find yourself needing the flexibility of the C-style for loop, you can always embed some literal JavaScript in your CoffeeScript by wrapping it in backticks (`...`):

`for (i=start; (step > 0 && i < end) || (step < 0 && i > end); i+=step) {
     array.push(i);
 }`

Upvotes: 1

Lucero
Lucero

Reputation: 60190

This may do what you want, assuming that you want the numbers from start to end as items in the array variable:

array = (i for i in [start...end])

Upvotes: 2

Related Questions