CoffeeScriptを書いてみたよ その2

昨日のCoffeeScriptの続き。だんだん構文が難しくなってきた!

可変長引数

# 可変長引数
func = (x, y, z...) ->
  console.log x
  console.log y
  console.log z

func 1, 2, 3, 4, 5, 6  # 1, 2, [3, 4, 5, 6]

# ???
func 1, 2, [3, 4, 5, 6]...

forループ

# for
console.log i for i in [1, 2, 3]  # 1, 2, 3
console.log i for i in [3..1]     # 3, 2, 1

# each/forEach, map
items = (i for i in [1, 2, 3])
console.log items  # [1, 2, 3]

# select/filter
strings = (s for s in ['aaa', 'aba', 'aca', 'abb'] when s[1] == 'b')
console.log strings  # ['aba', 'abb']

console.log (i for i in [1..10] by 2)  # [1, 3, 5, 7, 9]
console.log (i for i in [1..10] by 3)  # [1, 4, 7, 10]

# for-in
obj =
  a: 1
  b: 2
  c: 3
ret = for key, value of obj
  key + ': ' + value
console.log ret  # ['a: 1', 'b: 2', 'c: 3']

# for-in (hasOwnProperty)
ret = for own key, value of obj
  key + ': ' + value
console.log ret  # ['a: 1', 'b: 2', 'c: 3']

while/untilループ

# while修飾子?
i = 0; n = 5
console.log(i) while i++ < n  # 1, 2, 3, 4, 5

# until修飾子?
i = 0; n = 5
console.log(i) until i++ > n  # 1, 2, 3, 4, 5, 6

# while
num = 10
str = while num -= 1
  num
console.log str  # [9, 8, 7, 6, 5, 4, 3, 2, 1]


だんだん覚えられなくなってきた……
でもまあ、継続して書けば慣れる……はず!