Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Some nice examples, if a bit unfair since the JS is clearly compiled from the CoffeeScript rather than hand-coded. In fact, the last example reveals a bug in CoffeeScript—the function

    (x, y) ->
      for game_piece in @game_pieces
        if game_piece.is_at x, y
          @held_item = game_piece
          @held_item.start_dragging x, y
          break
compiles to

    function(x, y) {
        var game_piece, _i, _len, _ref, _results;
        _ref = this.game_pieces;
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          game_piece = _ref[_i];
          if (game_piece.is_at(x, y)) {
            this.held_item = game_piece;
            this.held_item.start_dragging(x, y);
            break;
          }
        }
        return _results;
      }
Notice that _results is initialized as an empty array... and is never modified, making it an utterly pointless return value. What's happening is that the CoffeeScript compiler has both implicit returns and list comprehensions, which means that it tries to return an array of all the values in the loop. All well and good, but the compiler doesn't try to do a list comprehension when there's a break... and yet it creates the frivolous _results variable anyway.

Obviously I'm a fan of CoffeeScript; this is a minor bug and I expect it to be fixed. But let's be fair in making the case for it. Well-written JavaScript will always look better than CoffeeScript output; it just takes a lot more work.



The proper way to avoid the return _results is just put a blank return statement in the last line of the function.

    (x, y) ->
      for game_piece in @game_pieces
        if game_piece.is_at x, y
          @held_item = game_piece
          @held_item.start_dragging x, y
          break
      return


To be fair, lack of optimization by a compiler is not a bug--unless it claims to do that kind of optimization.


Well, there was a related inconsistency which was certainly a bug. And it's now fixed: https://github.com/jashkenas/coffee-script/issues/1669




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: