My first CoffeeScript: An angular filter

I finally started writing my first CoffeeScript today. I’m working on a very complicated AngularJS app, so this is probably the worst time to be trying something new, but since Angular directives, filters, etc. are all of a very similar boilerplate format, this actually seemed like a good time to me to give it a shot. Since I know what the output should look like, I was hoping that I’d have an easier time writing my input in the beginning.

I started by writing a very simple filter that takes advantage of Javascript’s join method:

angular.module('campusJobApp').filter 'joinBy', ->
  (input, delimiter) -> (input || []).join delimiter || ','

And sure enough, this actually came out as a very reasonable-looking Angular filter in Javascript:

// Generated by CoffeeScript 1.7.1
(function() {
  angular.module('campusJobApp').filter('joinBy', function() {
    return function(input, delimiter) {
      return (input || []).join(delimiter || ',');
    };
  });

}).call(this);

//# sourceMappingURL=joinBy.map

With this success, I gave it a shot with something more complicated:

angular.module('campusJobApp')
    .filter 'idsToObjects', ['majors', (majors) ->
        (items, returnAttr) ->

            filtered = []

            getMajor = (major) ->
              majors.get {majorId: major},
                (res) -> filtered.push res,
                (res) -> #TODO: handle error

            getMajor(item) for item in items

            if returnAttr?
              [item[returnAttr] for item in items]
            else
              filtered

    ]

I like the feel of CoffeeScript, though I am much more used to just regular Javascript, and I’m concerned that I might get myself into trouble by misunderstanding or misusing CoffeeScript’s syntax (particularly the optionality of parentheses). This would be a much more egregious sin in Javascript, given the notorious type coercion and other silent ‘features’ that I could accidentally introduce into my code if I don’t know what I’m doing.

The other thing that I’m uncertain about is the mixing of CoffeeScript and Javascript. Most of my project is written in Javascript. The reason I’m able to get away with practicing CoffeeScript is that I’m using PyCharm, which watches and automatically compiles languages like CoffeeScript and SASS down to JS and CSS as I write them, so from the deployment perspective I don’t have to add the compilers to the asset filter. That being said, it will likely make it harder for other developers to edit my code if they (a) aren’t familiar with the language or (b) will have to pre-compile their changed code on their own, since I haven’t included the compilers as part of the asset pipeline.