How do I convert a JavaScript forEach loop/function to CoffeeScript

Edward J. Stembler picture Edward J. Stembler · Jun 14, 2012 · Viewed 31.6k times · Source

Background: I'm trying to convert some JavaScript code which uses the the Crossfilter library with D3.js data visualization library into CoffeeScript.

What is the best way to convert a JavaScript forEach loop/function into CoffeeScript?

Here's the JavaScript code:

// A little coercion, since the CSV is untyped.
flights.forEach(function(d, i) {
    d.index = i;
    d.date = parseDate(d.date);
    d.delay = +d.delay;
    d.distance = +d.distance;
});

Can CoffeeScript do an in-line function inside a loop? Right now I'm guess I need it broken out into a function and loop:

coerce = (d) ->
     d.index    = 1
     d.date     = parseDate(d.date)
     d.delay    = +d.delay
     d.distance = +d.distance

coerce(flights) for d in flights

Answer

hvgotcodes picture hvgotcodes · Jun 14, 2012

use a comprehension

for d, i in flights
  console.log d, i

The code above translates to

var d, i, _i, _len;

for (i = _i = 0, _len = flights.length; _i < _len; i = ++_i) {
  d = flights[i];
  console.log(d, i);
}

so you can see d and i are what you want them to be.

Go here and search for "forEach" for some examples.

Finally, look at the first comment for some more useful info.