Sunday, June 24, 2012

Functional JavaScript with LiveScript, Mocha, and ExpectThat

I've been playing with LiveScript a bit lately and have really been enjoying it! If you haven't heard of LiveScript, it's a "...fork of Coco, which is in turn derived from CoffeeScript..."  (LiveScript Overview Page). It provides more features than Coco and CoffeeScript including several that assist in writing code in a more functional style.

Here's a quick example of a test written in LiveScript for Mocha and ExpectThat:

This shows off a couple of the features that help you write in a functional style with LiveScript. The first is the use of pattern matching within the isWeekend function. The second is the use of the pipe-forward operator when calling the isWeekend function.

The pattern matching syntax gives you a concise way of defining a basic switch statement in JavaScript. The pipe-forward operator allows you to compose things together. In the example above, the string 'sun' (which also could have been written in LiveScript as \sun) is being passed into the isWeekend function. This becomes even more powerful when the value to be passed into the next function is coming from another function, as shown in this example:

F# has these same concepts and many more, which makes LiveScript + F# a compelling combination!

There are a number of additional LiveScript features that assist in using a functional style. For more examples of LiveScript with Mocha and ExpectThat visit https://github.com/dmohl/expectThat/tree/master/example/mocha-LiveScript. To learn more about LiveScript, see a number of examples, and/or get setup for use, visit the LiveScript site at http://gkz.github.com/LiveScript/.

No comments:

Post a Comment