CoffeeScript


                2012/01/18
       h13i32maru@Twitter
         maruyama-r@KLab
自己紹介
• 丸山 亮(h13i32maru) 最近はJSを触ってます
• KLab株式会社所属
32   http://blog.h13i32maru.jp

     http://twitter.com/h13i32maru

     https://www.facebook.com/ryo.maruyama

     https://github.com/h13i32maru
JavaScript
JavaScriptって結構大変

• ファイルのinclude機構が無い
• プロトタイプ指向
• 動的スコープ
• 不思議なthis
• などなど
そこで、
CoffeeScript
CoffeeScriptとは

• JavaScriptにコンパイル可能な小さな言語
• RubyやPythonから色々取り込んでる
• @jashkenasが作ってる
 - 他にもruby-processingなど
• http://coffeescript.org/
Language Reference
        翻訳してみた
http://d.hatena.ne.jp/h13i32maru/
      20120119/1326955300
関数
func = (arg1, arg2) -> arg1 * arg2




func = (arg1, arg2) ->
 x = arg1 * arg2
 x * x
レキシカルスコープ
outer = 1
changeNumbers = ->
  inner = -1
  outer = 10

inner = 20

changeNumbers()

alert [outer, inner]
内包表記
eat food for food in ['toast', 'cheese', 'wine']




countdown = (num * num for num in [10..1])




yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
   "#{child} is #{age}"
配列のスライスとレンジ
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
middle = numbers[3..6]




numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[3..6] = [-3, -4, -5, -6]
比較
if x is 0

if y isnt 100



cholesterol = 127

healthy = 200 > cholesterol > 60
存在演算子
solipsism = true if mind? and not world?




zip = lottery.drawWinner?().address?.zipcode
クラスと継承
class Animal
  constructor: (@name) ->

  move: (meters) ->
    alert @name + " moved #{meters}m."

class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5
展開代入
theBait   = 1000
theSwitch = 0

[theBait, theSwitch] = [theSwitch, theBait]
関数束縛
Account = (customer, cart) ->
  @customer = customer
  @cart = cart

  $('.shopping_cart').bind 'click', (event) =>
    @customer.purchase @cart
文字列内変数展開
author = "Wittgenstein"
quote = "A picture is a fact. -- #{ author }"
全てが式
i = 0
res = while i isnt 10
  i++
  i * i

#1,4,9,16,25,36,49,64,81,100
alert res
ビルドシステム

• Cake : CoffeeScript付属のビルドシステム
• MakeやRakeみたいなもの
• ファイルの結合もできるよ!
他にも

• YAML的なオブジェクトの書き方
• if/unlessの後置記法
• JavaScriptの埋め込み
• ヒアドキュメント
• 可変引数
• デフォルト引数 などなど
翻訳をしてみて

• コードのおかげでなんとなく翻訳できる
• 7600文字の翻訳で10時間くらい
• ジョークっぽいのがあったけど上手く訳せず
• 実は既に翻訳があったりするwww
おわり

CoffeeScript