CoffeeScript Wishlist
I’ve been working a bit with CoffeeScript lately, and I’ve pretty much fallen in love. But as a Rubyist, I find that I miss a few things. Allow me to explain.
Over the Christmas holiday, I found a GitHub project called Github Fantasy League, which cleverly quantifies a GitHub user’s open source “score” by assigning point values to certain activities, such as creating a pull request or filing an issue. The project is written in CoffeeScript, and I decided I would find something to fix so I could work in the CoffeeScript file and file a pull request. My change was modest; I decided that the form needed validation. So I spent some time looking over the CoffeeScript syntax, and I rewrote one particular function thusly:
Original
$('#username').bind('keypress', (e) =>
if (e.keyCode == 13 )
$('.score-trigger').click()
)
My Edit
$('#username').bind('keypress', (e) =>
$('.score-trigger').click() if e.keyCode == 13)
This was a few months ago, and I now realize I could’ve made it still more simple:
$('#username').bind('keypress', (e) =>
$('.score-trigger').click() if e.keyCode is 13)
The elegance of that line asounded me, and it reads like natural English: “The score-trigger element [should receive a] click if the keyCode is 13.” That, to me, is the hallmark of a great language: readable syntax.
Wish List
But while I love so much about CoffeeScript, a few things don’t quite make sense to me. For example, it uses Ruby’s unless
keyword, but still prefer’s JavaScript’s native else if
conditional for control flow to Ruby’s elsif
. Now, I suppose this is a matter of personal preference. That is, elsif
isn’t a word, where as else if
is proper English. But I feel like if CoffeeScript is going to adopt certain Ruby idioms, it should be done uniformly. Thus, I’d prefer to use elsif
.
The second thing I’d like is a ternary operator. I try not to overuse this expression, but if a bit of logic can be placed on one line with the use of a ternary operator, I often prefer it. Consider a simple function to check whether a number is even or odd:
isEven = (number) ->
if number % 2 is 0
true
else
false
This is the pefect case for a ternary operator:
isEven = (number) ->
number % 2 == 0 ? true : false
#=> not correct CoffeeScript
I suppose you could argue that writing the function that way is too terse. But stylistically speaking, having a single word on a line bothers me. It’s inefficient and could be cleaned up. But I suppose that’s a matter of personal preference.
Conclusion
I’ve very much enjoyed the little CoffeeScript I’ve done, and I look forward to more complex projects in the near future. However, I do wish that it had the elsif
construction (or even supported either else if
or elsif
just like it supports ==
or is
) and supported the ternary operator. I imagine I’ll find more as I continue to dive into the language.
What features do you wish CoffeeScript had?