Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper syntax for array.forEach() in coffeescript

I have a following code in coffeescript to recursively list directories (converted from javascript):

fs = require 'fs'

walk = (dir, done) ->
  results = []
  fs.readdir dir, (err, list) ->
    return done(err) if err
    pending = list.length
    return done(null, results) unless pending
    list.forEach (file) ->
      file = "#{dir}\\#{file}"
      fs.stat file, (err, stat) ->
        if stat and stat.isDirectory()
          walk file, (err, res) ->
            results = results.concat(res)
            done null, results  unless --pending
        else
          results.push file
          done null, results  unless --pending

walk __dirname, (err, results) ->
  throw err if err
  console.log results

As you can see I am using list.forEach (file) -> and it's working. But when I try to replace it with for file in list then it doesn't work properly. What do I do wrong?

like image 846
vivanov Avatar asked Jul 19 '12 18:07

vivanov


People also ask

What is array forEach?

JavaScript Array forEach() The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.

How do you make a function in CoffeeScript?

The function keyword is eliminated in CoffeeScript. To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below.

How do I use CoffeeScript in HTML?

If you are looking to implement coffee script in html, take a look at this. You simple need to add a <script type="text/coffeescript" src="app. coffee"></script> to execute coffee script code in an HTML file.

How is forEach implemented in JavaScript?

The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element. Index (optional) - The current element's index number. Array (optional) - The array object to which the current element belongs.


1 Answers

You're defining a function in a loop. A common pitfall in JS. You'll need to close over the iterator.

for file in list then do (file) =>

like image 146
Michael Ficarra Avatar answered Oct 02 '22 14:10

Michael Ficarra