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 
                The syntax of function in CoffeeScript is simpler as compared to JavaScript. In CoffeeScript, we define only function expressions. The function keyword is eliminated in CoffeeScript. To define a function here, we have to use a thin arrow (->).
Officially, there is no proper way to break out of a forEach loop in javascript. Using the familiar break syntax will throw an error. If breaking the loop is something you really need, it would be best to consider using a traditional loop.
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.
The direct translation is:
flights.forEach (d, i) ->   d.index = i   d.date = parseDate(d.date)   d.delay = +d.delay   d.distance = +d.distance   or you can use an idiomatic version:
for d,i in flights   d.index = i   d.date = parseDate(d.date)   d.delay = +d.delay   d.distance = +d.distance 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With