Iterating over a string in coffeescript without having to create an array

coffeescript, javascript

Solution

It doesn't actually create an array if it doesn't have to. Look at the compiled JS. This CoffeeScript:

str = "hello"
for i in [0..(str.length-1)]
  alert(i)

Generates the following JavaScript:

var i, str, _i, _ref;

str = "hello";

for (i = _i = 0, _ref = str.length - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
  alert(i);
}

No array was actually created.

(Subtracting 1 to .length to avoid an undefined)

Problem

I have several places in my code where I need to iterate over a string and perform operations char by char. My node.js application needs to do this dozens of times per request and often the length of the strings can be fairly long. The only way I've seen to convert a javascript like the one below into coffeescript is to create an array based on the length of the string. The problem with this I have is it's an extra thing to do on the hardware side, takes up extra memory, and just seems unnecessary (my node application processes dgrams - up to thousands a second - so all this extra work adds up). The JavaScript way: ``` for(var i = 0; i < str.length; i++) { /* Do stuff with str here */ } ``` The suggested CoffeeScript way ``` for i in [0..str.length] # Do stuff here ``` Again, I think it's silly to force the creation of an array object when the traditional for loop doesn't have to mess with that step from a hardware perspective. My only work around I've found is to use while loops like: ``` i = 0 while i < str.length # Do stuff i++ ``` While that works, that's far more verbose than even the straight JavaScript way of just using a simple for loop. Is there a way to use a for loop in CoffeeScript without having to generate superfluous arrays in order to perform basic iterations?

Original source