CoffeeScript
   Petr Pokorný
Obsah


Co to je?
Proč to používat?
Jak to vypadá?
Jak to rozchodit?
Co to je?
Co to je?

CoffeeScript is a little language that compiles
into JavaScript.
Co to je?

CoffeeScript is a little language that compiles
into JavaScript.




The code compiles one-to-one into the
equivalent JS, and there is no interpretation
at runtime.
JavaScript je v jádru docela dobrý jazyk, ale…
JavaScript je v jádru docela dobrý jazyk, ale…


“   JavaScript had to look like Java only less so, be
    Java’s dumb kid brother or boy-hostage sidekick.
JavaScript je v jádru docela dobrý jazyk, ale…


“   JavaScript had to look like Java only less so, be
    Java’s dumb kid brother or boy-hostage sidekick.

    Plus, I had to be done in ten days or something
    worse than JavaScript would have happened.
                                                     ”
                                      — Brendan Eich
Proč to používat?
Proč to používat?


Rychlejší vývoj
Proč to používat?


Rychlejší vývoj

Méně bugů
Proč to používat?


Rychlejší vývoj

Méně bugů

Lepší čitelnost
Jak to vypadá?




JavaScript     CoffeeScript
Functions


var cube, square;
square = function(x) {
   return x * x;           square = (x) -> x * x
};
cube = function(x) {       cube = (x) -> square(x) * x
   return square(x) * x;
};




      JavaScript                CoffeeScript
Objects

var kids = {            kids =
   brother: {             brother:
     name: "Max",           name: "Max"
     age: 11                age: 11
   },                     sister:
   sister: {                name: "Ida"
     name: "Ida",           age: 9
     age: 9
   }
};



      JavaScript              CoffeeScript
If, Else, Conditional Assignment


var date, mood;
if (singing) {                mood = greatlyImproved if singing
  mood = greatlyImproved;
}
if (happy && knowsIt) {       if happy and knowsIt
  clapsHands();                 clapsHands()
  chaChaCha();                  chaChaCha()
} else {                      else
  showIt();                     showIt()
}
date = friday ? sue : jill;   date = if friday then sue else jill



        JavaScript                    CoffeeScript
OOP
var Animal, Horse, Snake, sam, tom;
var __hasProp = Object.prototype.hasOwnProperty, __extends =
                                                                     class Animal
function(child, parent) {                                              constructor: (@name) ->
  for (var key in parent) {
 if (__hasProp.call(parent, key)) child[key] = parent[key]; }
  function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
                                                                       move: (meters) ->
child.prototype = new ctor; child.__super__ = parent.prototype;          alert @name +" moved "+ meters +"m."
return child;};Animal = (function() {
  function Animal(name) { this.name = name; }
  Animal.prototype.move = function(meters) {                         class Snake extends Animal
     return alert(this.name + " moved " + meters + "m.");
  };                                                                   move: ->
return Animal;})();
Snake = (function() { __extends(Snake, Animal); function
                                                                         alert "Slithering..."
Snake() {     Snake.__super__.constructor.apply(this, arguments);        super 5
} Snake.prototype.move = function() {      alert("Slithering...");
return Snake.__super__.move.call(this, 5); }; return
Snake;})();                                                          class Horse extends Animal
Horse = (function() { __extends(Horse, Animal); function
Horse() {                                                              move: ->
  }
    Horse.__super__.constructor.apply(this, arguments);                  alert "Galloping..."
Horse.prototype.move = function() {                                      super 45
    alert("Galloping...");    return
Horse.__super__.move.call(this, 45);
}; return Horse;})();                                                sam = new Snake "Sammy the Python"
sam = new Snake("Sammy the Python");
tom = new Horse("Tommy the Palomino");                               tom = new Horse "Tommy the Palomino"




                  JavaScript                                                    CoffeeScript
Na co jste zvyklí z Pythonu
Loops

# Eat lunch.
for food in ['toast', 'cheese', 'wine']:
  eat(food)



# Eat lunch.
eat food for food in ['toast', 'cheese', 'wine']
Loops

# Eat lunch.
for food in ['toast', 'cheese', 'wine']:
  eat(food)



# Eat lunch.
eat food for food in ['toast', 'cheese', 'wine']


var food, _i, _len, _ref;
_ref = ['toast', 'cheese', 'wine'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  food = _ref[_i];
  eat(food);
}
Loops

for key in {‘foo’: ‘bar’}

for key, value in {‘foo’: ‘bar’}.items()




for key of {foo: ‘bar’}

for key, value of {foo: ‘bar’}
Ranges

for i in range(1, 10)

for i in range(10, 1, -1)

for i in range(1, 10, 2)


for i in [1..9] # nebo [1...10]

for i in [10..2]

for i in [1..9] by 2
Comprehensions


short_names = [name for name in list if len(name) < 5]




shortNames = (name for name in list when name.length < 5)
Slicing

my_list[3:6]

my_list[3:]

my_list[:-3]


myList[3..5]

myList[3..]

myList[...-3]
Slicing

my_list[3:6] = [1, 2, 3]

my_list[3:]

my_list[:-3]


myList[3..5] = [1, 2, 3]

myList[3..]

myList[...-3]
Splats
(a.k.a. argument list unpacking)




def foo(bar, *args): pass




foo = (bar, args...) ->
Chained Comparisons



 cholesterol = 127

 healthy = 200 > cholesterol > 60
more...
The Existential Operator


           alert "I knew it!" if elvis?




if (typeof elvis !== "undefined" && elvis !== null) {
  alert("I knew it!");
}
Destructuring Assignment

theBait = 1000
theSwitch = 0

[theBait, theSwitch] = [theSwitch, theBait]



weatherReport = (location) ->
  # Make an Ajax request to fetch the weather...
  [location, 72, "Mostly Sunny"]

[city, temp, forecast] = weatherReport "Berkeley, CA"
Fat arrow – binding this


Account = (customer, cart) ->
  @customer = customer
  @cart = cart

  $('.shopping_cart').bind 'click', (event) =>
    @customer.purchase @cart
String Interpolation


author = "Wittgenstein"
quote = "A picture is a fact. -- #{author}"

sentence = "#{ 22 / 7 } is a decent approximation of π"
Jak to rozchodit?
The CoffeeScript compiler is
itself written in CoffeeScript.
nodejs.org
Node Package Manager
$ curl http://npmjs.org/install.sh | sh

$ npm install -g coffee-script
$ coffee --watch --compile *.coffee


19:45:31 - compiled   myscript.coffee
19:47:22 - compiled   myscript.coffee
In myscript.coffee,   too many ) on line 39
19:47:40 - compiled   myscript.coffee
19:48:10 - compiled   myscript.coffee
19:48:47 - compiled   myscript.coffee
In myscript.coffee,   Parse error on line 3: Unexpected 'INDENT'
19:49:23 - compiled   myscript.coffee
<script src="/path/to/coffee-script.js"></script>
<script type="text/coffeescript">
  $(document).ready -> alert "Your DOM is ready."
</script>
Odkazy
CoffeeScript homepage
http://jashkenas.github.com/coffee-script/


node.js
http://nodejs.org/

npm
http://npmjs.org/

Introduction to CoffeeScript
http://screencasts.org/episodes/introduction-to-coffeescript/

Js2Coffee – The JavaScript to CoffeeScript compiler.
http://ricostacruz.com/js2coffee/

CoffeeScript

  • 1.
    CoffeeScript Petr Pokorný
  • 2.
    Obsah Co to je? Pročto používat? Jak to vypadá? Jak to rozchodit?
  • 3.
  • 4.
    Co to je? CoffeeScriptis a little language that compiles into JavaScript.
  • 5.
    Co to je? CoffeeScriptis a little language that compiles into JavaScript. The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime.
  • 6.
    JavaScript je vjádru docela dobrý jazyk, ale…
  • 7.
    JavaScript je vjádru docela dobrý jazyk, ale… “ JavaScript had to look like Java only less so, be Java’s dumb kid brother or boy-hostage sidekick.
  • 8.
    JavaScript je vjádru docela dobrý jazyk, ale… “ JavaScript had to look like Java only less so, be Java’s dumb kid brother or boy-hostage sidekick. Plus, I had to be done in ten days or something worse than JavaScript would have happened. ” — Brendan Eich
  • 9.
  • 10.
  • 11.
  • 12.
    Proč to používat? Rychlejšívývoj Méně bugů Lepší čitelnost
  • 13.
  • 14.
    Functions var cube, square; square= function(x) { return x * x; square = (x) -> x * x }; cube = function(x) { cube = (x) -> square(x) * x return square(x) * x; }; JavaScript CoffeeScript
  • 15.
    Objects var kids ={ kids = brother: { brother: name: "Max", name: "Max" age: 11 age: 11 }, sister: sister: { name: "Ida" name: "Ida", age: 9 age: 9 } }; JavaScript CoffeeScript
  • 16.
    If, Else, ConditionalAssignment var date, mood; if (singing) { mood = greatlyImproved if singing mood = greatlyImproved; } if (happy && knowsIt) { if happy and knowsIt clapsHands(); clapsHands() chaChaCha(); chaChaCha() } else { else showIt(); showIt() } date = friday ? sue : jill; date = if friday then sue else jill JavaScript CoffeeScript
  • 17.
    OOP var Animal, Horse,Snake, sam, tom; var __hasProp = Object.prototype.hasOwnProperty, __extends = class Animal function(child, parent) { constructor: (@name) -> for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; move: (meters) -> child.prototype = new ctor; child.__super__ = parent.prototype; alert @name +" moved "+ meters +"m." return child;};Animal = (function() { function Animal(name) { this.name = name; } Animal.prototype.move = function(meters) { class Snake extends Animal return alert(this.name + " moved " + meters + "m."); }; move: -> return Animal;})(); Snake = (function() { __extends(Snake, Animal); function alert "Slithering..." Snake() { Snake.__super__.constructor.apply(this, arguments); super 5 } Snake.prototype.move = function() { alert("Slithering..."); return Snake.__super__.move.call(this, 5); }; return Snake;})(); class Horse extends Animal Horse = (function() { __extends(Horse, Animal); function Horse() { move: -> } Horse.__super__.constructor.apply(this, arguments); alert "Galloping..." Horse.prototype.move = function() { super 45 alert("Galloping..."); return Horse.__super__.move.call(this, 45); }; return Horse;})(); sam = new Snake "Sammy the Python" sam = new Snake("Sammy the Python"); tom = new Horse("Tommy the Palomino"); tom = new Horse "Tommy the Palomino" JavaScript CoffeeScript
  • 18.
    Na co jstezvyklí z Pythonu
  • 19.
    Loops # Eat lunch. forfood in ['toast', 'cheese', 'wine']: eat(food) # Eat lunch. eat food for food in ['toast', 'cheese', 'wine']
  • 20.
    Loops # Eat lunch. forfood in ['toast', 'cheese', 'wine']: eat(food) # Eat lunch. eat food for food in ['toast', 'cheese', 'wine'] var food, _i, _len, _ref; _ref = ['toast', 'cheese', 'wine']; for (_i = 0, _len = _ref.length; _i < _len; _i++) { food = _ref[_i]; eat(food); }
  • 21.
    Loops for key in{‘foo’: ‘bar’} for key, value in {‘foo’: ‘bar’}.items() for key of {foo: ‘bar’} for key, value of {foo: ‘bar’}
  • 22.
    Ranges for i inrange(1, 10) for i in range(10, 1, -1) for i in range(1, 10, 2) for i in [1..9] # nebo [1...10] for i in [10..2] for i in [1..9] by 2
  • 23.
    Comprehensions short_names = [namefor name in list if len(name) < 5] shortNames = (name for name in list when name.length < 5)
  • 24.
  • 25.
    Slicing my_list[3:6] = [1,2, 3] my_list[3:] my_list[:-3] myList[3..5] = [1, 2, 3] myList[3..] myList[...-3]
  • 26.
    Splats (a.k.a. argument listunpacking) def foo(bar, *args): pass foo = (bar, args...) ->
  • 27.
    Chained Comparisons cholesterol= 127 healthy = 200 > cholesterol > 60
  • 28.
  • 29.
    The Existential Operator alert "I knew it!" if elvis? if (typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
  • 30.
    Destructuring Assignment theBait =1000 theSwitch = 0 [theBait, theSwitch] = [theSwitch, theBait] weatherReport = (location) -> # Make an Ajax request to fetch the weather... [location, 72, "Mostly Sunny"] [city, temp, forecast] = weatherReport "Berkeley, CA"
  • 31.
    Fat arrow –binding this Account = (customer, cart) -> @customer = customer @cart = cart $('.shopping_cart').bind 'click', (event) => @customer.purchase @cart
  • 32.
    String Interpolation author ="Wittgenstein" quote = "A picture is a fact. -- #{author}" sentence = "#{ 22 / 7 } is a decent approximation of π"
  • 33.
  • 34.
    The CoffeeScript compileris itself written in CoffeeScript.
  • 35.
  • 36.
    Node Package Manager $curl http://npmjs.org/install.sh | sh $ npm install -g coffee-script
  • 37.
    $ coffee --watch--compile *.coffee 19:45:31 - compiled myscript.coffee 19:47:22 - compiled myscript.coffee In myscript.coffee, too many ) on line 39 19:47:40 - compiled myscript.coffee 19:48:10 - compiled myscript.coffee 19:48:47 - compiled myscript.coffee In myscript.coffee, Parse error on line 3: Unexpected 'INDENT' 19:49:23 - compiled myscript.coffee
  • 38.
    <script src="/path/to/coffee-script.js"></script> <script type="text/coffeescript"> $(document).ready -> alert "Your DOM is ready." </script>
  • 39.
    Odkazy CoffeeScript homepage http://jashkenas.github.com/coffee-script/ node.js http://nodejs.org/ npm http://npmjs.org/ Introduction toCoffeeScript http://screencasts.org/episodes/introduction-to-coffeescript/ Js2Coffee – The JavaScript to CoffeeScript compiler. http://ricostacruz.com/js2coffee/