Thursday, February 25, 2010

CoffeeScript

I've just found out about CoffeeScript which is a really neat way to make JavaScript look nicer. It can be compiled on the fly to real JavaScript. Here's one example I just wrote:
fibonacci: (x)->
return 0 if x == 0
return 1 if x == 1
return fibonacci(x-1) + fibonacci(x-2)

alert fibonacci 10
which compiles into this:
var fibonacci;
fibonacci = function fibonacci(x) {
if (x === 0) {
return 0;
}
if (x === 1) {
return 1;
}
return fibonacci(x - 1) + fibonacci(x - 2);
};
alert(fibonacci(10));
pretty sweet huh?

2 comments:

Anonymous said...

Here is a one-liner for Fibonacci:

fib = (n) -> if (n > 1) then (fib(n - 1) + fib(n - 2)) else n

You're the first google result for "coffeescript fibonacci" so that's how I found this post.

vanss said...

SEO Specialist http://www.vanss.org