Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrementing for loop in coffeescript

I know how to do a incrementing for loop in coffeescript such as:

Coffeescript:

for some in something 

Generated Javascript:

for (_i = 0, _len = something.length; _i < _len; _i++) 

How do I create a decrementing for loop similar to this in Coffeescript?

for (var i = something.length-1; i >= 0; i--) 
like image 209
John Avatar asked Oct 27 '11 18:10

John


People also ask

How do you use a loop in CoffeeScript?

JavaScript provides while, for and for..in loops. The loops in CoffeeScript are similar to those in JavaScript. while loop and its variants are the only loop constructs in CoffeeScript. Instead of the commonly used for loop, CoffeeScript provides you Comprehensions which are discussed in detail in later chapters.

What is CoffeeScript used for?

CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehension and destructuring assignment.


2 Answers

EDIT: As of CoffeeScript 1.5 by -1 syntax is supported.

First, you should familiarize yourself with the by keyword, which lets you specify a step. Second, you have to understand that the CoffeeScript compiler takes a very naïve approach to loop endpoints (see issue 1187, which Blender linked to), which means that

for some in something by -1 # don't do this!!! 

will result in an infinite loop—it starts at index 0, increments the index by -1, and then waits until the index hits something.length. Sigh.

So you need to use the range loop syntax instead, which lets you specify those endpoints yourself—but also means you have to grab the loop items yourself:

for i in [something.length - 1..0] by -1   some = something[i] 

Obviously that's pretty messy. So you should strongly consider iterating over something.reverse() instead. Just remember that reverse() modifies the array that you call it on! If you want to preserve an array but iterate over it backwards, you should copy it:

for some in something.slice(0).reverse() 
like image 124
Trevor Burnham Avatar answered Sep 24 '22 04:09

Trevor Burnham


As of coffee-script 1.5.0 this is supported:

for item in list by -1   console.log item 

This will translate into

var item, _i; for (_i = list.length - 1; _i >= 0; _i += -1) {   item = list[_i];   console.log(item); } 
like image 35
Evan Moran Avatar answered Sep 24 '22 04:09

Evan Moran