Rambling Labs Blog Ramblings on software development

  • The joy of writing CoffeeScript

    I have been a fan of JavaScript for a while now, and I have dived into the CoffeeScript world for the last month or so.

    Guess what?
    I love it! It's been a great experience so far.

    Definitely the one thing that I'm loving the most right now about CoffeeScript is the syntactic sugar.
    It's basically a lot of simple shorthands for certain things (the -> is so handy). Take this example (and ignore what the excluded methods are doing):

    I had this:

    class BuildUtils
      combine_source_files: (callback) ->
        self = @
        fs.readdir './src', (err, files) ->
          self.error_handler err
          content = new Array()
    
          files = files.sort()
          for file, index in files then do (file, index) ->
            unless file.indexOf('.') is 0
              fs.readFile "./src/#{file}", 'utf8', (err, fileContent) ->
                self.error_handler err
                content[content.length] = fileContent
    
                if index is files.length - 1
                  callback content
    

    And changed it to this:

    class BuildUtils
      combine_source_files: (callback) ->
        self = @
        fs.readdir './src', (err, files) ->
          self.error_handler err
          content = new Array()
    
          files = files.sort()
          for file, index in files when file.indexOf('.') isnt 0 then do (file, index) ->
            fs.readFile "./src/#{file}", 'utf8', (err, fileContent) ->
              self.error_handler err
              content[content.length] = fileContent
    
              if index is files.length - 1
                callback content
    

    Did you spot it?
    Let's take a closer look:

    Had this:

    for file, index in files then do (file, index) ->
      unless file.indexOf('.') is 0
        # The code I want to run
    

    And got this afterwards:

    for file, index in files when file.indexOf('.') isnt 0 then do (file, index) ->
      # The code I want to run
    

    Yes, I know, it's a really simple change, and it's basically doing the same.
    But doesn't the second one read beautifully?

    This is how I read it:

    For file and index in files, when the file does not start with '.' then do..."

    What do you think?

  • blog comments powered by Disqus