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
Use a comprehension:
for d, i in flights
console.log d, i
The code above translates to:
let 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.