Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 670
Edward J. Stembler Avatar asked Jun 14 '12 15:06

Edward J. Stembler


People also ask

How do you define a function in CoffeeScript?

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 (->).

Can you break a forEach loop JavaScript?

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.


2 Answers

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.

like image 57
hvgotcodes Avatar answered Oct 03 '22 01:10

hvgotcodes


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 
like image 42
Scott Weinstein Avatar answered Oct 03 '22 01:10

Scott Weinstein