Tuesday, September 3, 2013

Introduction to LiveScript and its comparison with Coffesript

LiveScript is an indirect descendant of CoffeeScript with features to assist functional programming like pattern matching and function composition. In a manner similar to coffeescript, it too compiles to javascript and can be used to write expressive code with as little boilerplate code as possible.
Like coffeescript, it runs on node.js and can be installed using sudo npm install -g LiveScript command.
Here are some of the amazing features 

  • jQuery parenthesis are no longer required: $ \.content .find \.date-author .text!split ' ' .0
  • Partially apply operators to entire list:eg; this multiplies all list variables by 2.  map (* 2), [1 to 5] 
  • Usage of pipes to make the nested functions seem a lot less messy: [1 2 3] |> map (* 2) |> filter (> 3) |> fold1 (+)
  • Easily find the minimum/maximum from a list minimum [12 13 3 -16 101 56 0 23]
  • Partition a list into two lists neatly; [passed, failed] = partition (> 33), [30, 45, 35, 12, 50, 32, 66] will yield: passed = [45, 35, 50, 66] and failed = [30, 12, 32]

The site also offers a small Coffeescript to Livescript guide:

  • All => to ~>
  • All block comments ### to java styled comments /*  */
  • All undefined to void
  • Any range syntax [a..b] to this expressive syntax; [a to b]. similarly for [f...g], do [f til g]
  • In a similar manner, range syntax is changed from 'for x in [4..12]' to 'for x from 4 to 12'
  • The regular expression literals are also changed from /// to //
  • Functions having empty arguments can remove their parentheses
  • Constructor functions are also changed as the explicit constructor keyword becomes optional and is defined as a top level keyword.
  • Any calls to parent classes is done via super ... as super is a direct reference to the parent function itself.
  • For multi-line strings, the indentation after a line is treated only as a single space.
  • Special casing function literals here use a 'let' instead of a 'do' eg; do($ = jQuery) -> $
  • Javascript code literals only need a single 'quote' around them.
  • For property access, do not leave space around both sides of the dot. eg; z.x (here it is use to compose functions
Hope that these pointers might motivate someone to jump start into livescript.

No comments: