About Jamie on Software

Jamie on Software is the online journal of web developer and writer Jamie Rumbelow.

Jamie likes books, guitars, programming, open source and food. He writes about these things too. This is where he puts the things he writes.

Tags
Tweets
Feeds
We Love
Powered by Squarespace

Entries in coffeescript (1)

Monday
Sep122011

Syntax Sugar #4 - CoffeeScript one-liners

I'm a sucker for short, concise syntax. One of the beautiful features about CoffeeScript - the JavaScript/Ruby lovechild that I'm slowly learning to adore - is its single line function declaration. Using this powerful syntax one can write really expressive functions with terse code.

Let's demonstrate this with a quick function. Let's say we want to remove a specific element from an array. My first guess would be to write:

var arr = [ 1, 2, 3, 4 ];
delete arr[0]; // [ nil, 2, 3, 4 ]

The issue with this, of course, is that we are left with a stray nil. That's not particularly convenient if we're using the array a lot. Instead, let's write a function and patch it onto the Array class.

Array::remove = ( element ) -> 
    if (@indexOf(element)) > -1
        @splice @indexOf(element), 1

We're using the built-in splice() method to remove the element at the index of our element. That isn't such a bad first attempt, but it's not particularly terse or pleasant. Let's remove the repetition and move index's assignment into the conditional:

Array::remove = ( element ) ->
    if (index = @indexOf(element)) > -1
        @splice index, 1

We can use CoffeeScript's keyword syntax and bracketless method calling to clean it up a bit further:

Array::remove = ( element ) ->
    if (index = @indexOf element) isnt -1
        @splice index, 1

And finally we can push it all into one line:

Array::remove = ( e ) -> @splice i, 1 if (i = @indexOf e) isnt -1

If we compare this to the JavaScript it generates:

Array.prototype.remove = function(e) {
    var i;
    if ((i = this.indexOf(e)) !== -1) {
        return this.splice(i, 1);
    }
};

…it's a no-brainer. CoffeeScript is a wonderful way of making JavaScript cleaner, more concise and altogether much more pleasant to work with. I'd highly recommend downloading a copy and trying it out.