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:

describe "When testing for the weekend", ->
    weekend   = <[ sat sun ]>

    isWeekend = (dayOfWeek) ->
        | dayOfWeek in weekend => true
        | otherwise => false

    expectThat -> ('sun' |> isWeekend).should equal true

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:

describe "When testing for the weekend", ->
    weekend   = <[ sat sun ]>

    isWeekend = (dayOfWeek) ->
        | dayOfWeek in weekend => true
        | otherwise => false

    getDayOfWeek = -> 'sun'

    expectThat -> (getDayOfWeek() |> isWeekend).should equal true

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/.

Tagged with:  
  • N-D

    Hey,

    you can also use “!” (bang call) to replace ().
    And since, unlike Coffee (it’s from coco) you can space calls, to write
    expectThat -> isWeekend(getDayOfWeek()).should equal true
    you can do :
    expectThat -> isWeekend getDayOfWeek! .should equal true

    • Anonymous

      Thanks. These are both good points. Although, unfortunately some of the parens are still needed in the examples that I show in this post (at least with the current version of LiveScript).

      i.e.

      expectThat -> (getDayOfWeek! |> isWeekend).should equal true

      works as desired, but doesn’t have the same output as

      expectThat -> getDayOfWeek! |> isWeekend .should equal true

      • N-D

        These are needed because you’re using |>
        In my example, I’m not
        isWeekend getDayOfWeek! ….