Meadows of wild horses

Blog...

CoffeeScript Tutorial

| Comments

coffeescript.org

Functions

함수는 ->로 정의 합니다.

example-01.coffee
1
2
3
4
square = (x) -> x * x
cube   = (x) -> square(x) * x

alert cube(5)
example-01.js
1
2
3
4
5
6
7
8
9
10
var cube, square;

square = function(x) {
  return x * x;
};

cube = function(x) {
  return square(x) * x;
}
alert(cube(5));

함수 생성시 인자를 생성및 전달 할수 있습니다.

example-02.coffee
1
2
3
fill = (container, liquid = "coffee") ->
  "Filling the #{container} with #{liquid}…"
alert fill("cup")
example-2.js
1
2
3
4
5
6
7
8
9
10
var fill;

fill = function(container, liquid) {
  if (liquid == null) {
    liquid = "coffee";
  }
  return "Finling the " + container + " with " + liquid + "...";
};

alert(fill("cup"));

Objects and Arrays

Array는 ‘,’로 인자를 구분 하며 YAML과 같이 개행 문자로도 구분 가능 합니다.

example-03.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
song = ["do", "re", "mi", "fa", "so"]

singers = {Jagger: "Rock", Elvis: "Roll"}

bitlist = [
  1, 0, 0
  0, 0, 1
  1, 1, 0
]

kids =
  brother:
    name: "Max"
    age: 11
  sister:
    name: "Ida"
    age: 9
alert song.join("…")
example-03.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var bitlist, kids, singers, song;

song = ["do", "re", "mi", "fa", "so"]
singers = {
  Jagger: "Rokcer",
  Elvis: "Roll"
};

bitlist = [1, 0, 1, 0, 0, 1, 1 , 1, 0];

kids = {
  brother: {
    name: "Max",
    age: 11
  },
  sister: {
    name: "Ida",
    age: 9
  }
};
alert(song.join(" … "));
example-03-01.coffee
1
2
$('.account').attr class: 'active'
log object.class

Lexical Scoping and Variable Safety(지역변수)

changeNumbers = ->안에 outer값은 외부의 outer의 영향을 받지 않습니다. alert outeralert inner의 값은 각 110입니다.

example-04.coffee
1
2
3
4
5
6
7
outer = 1
changeNumbers = ->
  inner = -1
  outer = 10
inner = changeNumbers()

alert inner

If, Else, Unless, and Conditional Assignment

singing값이 참일때 mood = greatlyImproved를 리턴 합니다.

example-05-01.coffee
1
mood = greatlyImproved if singing

happyknowIt두개의 값이 참일때와 아닐때를 분류 합니다.

example-05-02.coffee
1
2
3
4
5
if happy and knowIt
  clapsHands()
  chaChaCha()
else
  showIt()

다른 언어의 3항 연산자와 같이 동작 합니다. friday값이 참일때는 sue 아닐때는 jill입니다.

example-05-03.coffee
1
date = if friday then sue else jill

Splats…

(점3개) Array를 잘라 낼수 있습니다. awardMedals contenders… contenders를 분할하여 awardMedals에 정의 됩니다. 여러개의 값이 있고 3개의 변수가 정의 되어 있을때 분할된 첫번째와 두번째는 개별 인자로 정의 되고 나머지 변수에 남은 Array값이 저장 됩니다.

example-06.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
gold = silver = rest = "unknown"

awardMedals = (first, second, others…) ->
  gold   = first
  silver = second
  rest   = others

contenders = [
  "Michael Phelps"
  "Liu Xiang"
  "Yao Ming"
  "Allyson Felix"
  "Shawn Johnson"
  "Roman Sebrle"
  "Guo Jingjing"
  "Tyson Gay"
  "Asafa Powell"
  "Usain Bolt"
]

awardMedals contenders

alert "Gold: " + gold
alert "Silver: " + siliver
alert "the Field: " + rest

Loops and Comprehensions

Array의 값은 in으로 가져올수 있습니다 이를 food에 정의 하고 eat함수에 인자로 전달 합니다. eat food.js에서 eat(food); 변환됩니다.

example-07.coffee
1
eat food for food in ['tast', 'cheese', 'wine']

Array값을 받을 변수 dish와 증가값 i정의 합니다. i0에서 1씩 증가 합니다.

example-07-01.coffee
1
2
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
  menu i + 1, dish for dish, i in courses

by는 반복문 실행시 1개씩이 아닌 2개씩 건너뜁니다.

example-07-011.coffee
1
evens = (x for x in [0..10] by 2)

반복문과 비교문을 같이 정의 합니다. isntfor문 안에서 if !=으로 변환 됩니다.

example-07-02.coffee
1
2
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'

name의 길이가 5 미만인 값만을 반환 받습니다.

example-07-03.coffee
1
shortNames = (name for name in list when name.length < 5)

10..1값들은 Array에 push해 반환 합니다. countdown값은 10,9,8,7,6,5….1값이 됩니다.

example-08.coffee
1
countdown = (num for num in [10..1])

ofkey: value를 반환 합니다. yearsOld의 key, value가 chile``age로 정의 됩니다. ages는 문장 3개를 받습니다.(push)

example-09.coffee
1
2
3
4
yearsOld = max: 10, ida: 9, tim: 11

ages = for child, age of yearOld
  "#{child} is #{age}"

whileuntil을 사용 할수 있습니다.

example-10.coffee
1
2
3
4
# Econ 101
if this.studyingEconomics
  buy() while supply > demand
  sell() until supply > demand
example-10-01.coffee
1
2
3
4
5
6
7
`num`값이 `0`될때까지 횟수 만큼 문자열을 반환 합니다.

# Nursey Rhyme
num = 6
lyrics = while num -= 1
  "#{num} little monkeys, jumping on the bed.
  One fell out and bumped his head."

coffeescript do의 대한 설명

When using a JavaScript loop to generate functions,
it's common to insert a closure wrapper
in order to ensure that loop variables are closed over,
and all the generated functions don't just share the final values.
CoffeeScript provides the `do` keyword,
which immediately invokes a passed function, forwarding any arguments.     
example-11.coffee
1
2
3
4
for filename in list
  do (filename) ->
    fs.readFile filename, (err, contents) ->
      compile filename, contents.toString()

Array Slicing and Splicing with Ranges

start값은 1, 2, 3값을 반환 합니다.

example-12.coffee
1
2
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
start = numbers[0..2]

...6보다 작은값(6까지가 아님)까지 입니다. 반환값은 4,5,6입니다.

example-12-01.coffee
1
middle = numbers[36]

6번째 자릿수 부터 가져 옵니다. 반환값은 7,8,9입니다.

example-12-02.coffee
1
end = numbers[6..]

0번째 부터 이므로 모든 값을 가져옵니다.

example-12-03.coffee
1
copy = numbers[..]

numvers[3..6] 자리에 값과 변경 합니다.

example-13.coffee
1
2
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[3..6] = [-3, -4, -5, -6]

Everything is an Expression (at least, as much as possible)

if/else if/else 구문 입니다. 비교를 2번 할수 있습니다. if~then~else는 3항 연산자와 같이 쓸수 있습니다.

example-14.coffee
1
2
3
4
5
6
7
8
9
grade = (student) ->
  if student.excellentWork
    "A+"
  else if student.okayStuff
    if student.triedHard then "B" else "B-"
  else
    "C"

eldest = if 24 > 21 then "Liz" else "Ike"

변수 선언과 동시에 계산이 가능 합니다.

example-15.coffee
1
six = (one = 1) + (two = 2) + (three = 3)

window의 값을 10개 분할합니다.(slice)

example-16.coffee
1
globals = (name for name of window)[010]

try/catch

try계산 하고 error가 catch되면 try된 값이 아닌 catch값이 리턴 됩니다.

example-17.coffee
1
2
3
4
5
6
alert(
  try
    nonexistent / underfined
  catch error
    "And the error is … ${error}"
)

Operators and Aliases

CoffeeScript    |     JavaScript
    is          |        ===
   isnt         |        !==
    not         |        !
    and         |        &&
    or          |        ||
true, yes, on   |       true
false, no, off  |       false
   @, this      |       this
    of          |       in
    in          |   no JS equivalent

if (ignition === true)와 같습니다.

example-18-01.coffee
1
launch() if ignition is on

(band !== Spinaltap)과 같습니다.

example-18-02.coffee
1
volume = 10 if band isnt SpinalTap

unless와 중복 되어 if ( answer !== false)`와 같습니다.

example-18-03.coffee
1
letTheWildRumpusBegin() unless answer is no

if (car.speed < limit)일때 실행과 같습니다.

example-18-04.coffee
1
if car.speed < limit then accelerate()

if (pick === 47 || pick === 92 || pick == 13)과 같습니다.

example-18-05.coffee
1
winner = yes if pick in [47, 92, 13]

print(inspect("My name is this.name));와 같습니다. @.js의 this를 의미 합니다.

example-18-06.coffee
1
print inspect "My name is #{@name}"

The Existential Operator

coffeescript에서 ?undefinednull값인지 비교 합니다. speed ?= 15speednull인지 검사 합니다.

example-19.coffee
1
2
3
4
solipsism = true if mind? and no world?

speed = 0
speed ?= 15

yetiundefiendnull이 아닐 경우 yeti값을 반환하고 아니라면 bear 를 반환 합니다. 3항 연산자와 같은 형식 입니다.

example-19-01.coffee
1
footprints = yeti ? "bear"

coffeescript의 ?..

The accessor variant of the existential operator ?.
can be used to soak up null references in a chain of properties.
Use it instead of the dot accessor . in cases where the base value may be null or undefined.
If all of the properties exist then you'll get the expected result,
 if the chain is broken, undefined is returned instead of the TypeError that would be raised otherwise. 
example-20.coffee
1
zip = lottery.drawWinner?().address?.zipcode

Classes, Inheritance, and Super

class를 선언하고 불러 올수 있습니다.

new [class name]을 선언해서 class를 사용 합니다. 사용된 SnakeHorse에서 extends Animal을 사용 하였으므로 class Animal을 사용 합니다.

example-21.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Animal
  constructor: (@name) ->

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

class Snake extends Animal
  move: ->
    alert "Slithering…"
    super 5

class Horse extends Animal
    move: ->
      alert "Galloping…"
      super 45

sam = new Snake "Sammy the Python"
tam = new Horse "Tommy the Palomino"

sam.move()
tom.move()

prototype ‘::’

::.prototype.의 줄임 표현 입니다. String::dasherizeString.prototype.dasherize로 변환 됩니다.

example-22.coffee
1
2
String::dasherize = ->
  this.replace /_/g, "-"

Destructuring Assignment

선언된 두개의 값을 교환 합니다.

example-22.coffee
1
2
3
4
theBait = 1000
theSwitch = 0

[theBait, TheSwitch] = [theSwitch, theBait]

여러값의 반환

리턴 값으로 locatioin, 72, Mostly Sunny값 3개를 한번에 반환 합니다.

example-23.coffee
1
2
3
4
weatherReport = (location) ->
  [location, 72, "Mostly Sunny"]

[city, temp, forecast] = weatherReport "Berkeley, CA"

object의 반환

futurists object 값을 반환 합니다.

example-24.coffee
1
2
3
4
5
6
7
8
9
10
futurists =
  sculptor: "Umberto Boccioni"
  painter: "Vladimir Burliuk"
  poet:
    name: "F.T Marinetti"
    address: [
      "Via Roma 42R"
      "Bellagio, Italy 22021"
    ]
{poet: {name, address: [street, city]}} = futurists

split의 반환 값으로 open, contents... close 3군데로 나누어 받습니다. contents...값은 마지막 값 하나를 제외 하고 모든 값을 받습니다.

example-25.coffee
1
2
3
tag = "<impossible>"

[open, contents, close] = tag.split("")

Function binding

->함수 선언전의 (customer, cart)처럼 전달 인자를 정의 해줄수 있습니다.

example-26.coffee
1
2
3
4
5
6
Account = (customer, cart) ->
  @customer = customer
  @cart = cart

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

Embedded JavaScript

coffeescript 안에서 JavaScript 사용하기 위해서는 backticks가 필요 합니다.

example-27.coffee
1
2
3
hi = `function() {
  return [document.title, "Hello JavaScript"].join(": ");
}`

Switch/When/Else

day값을 when으로 비교 하고 when에 해당 하지 않으면 else를 실행 합니다.

example-28.coffee
1
2
3
4
5
6
7
8
9
10
switch day
  when "Mon" then go work
  when "Tue" then go relax
  when "Thu" then go iceFishing
  when "Fri", "Sat"
    if day is bingoDay
      go bingo
      go dancing
  when "Sun" then go church
  else go work

Try/Catch/Finally

try 시도를 하고 결과 같으로 catach와 비교 하여 아니면 finally를 실행 합니다.

example-29.coffee
1
2
3
4
5
6
7
try
  allHellBreaksLoose()
  catsAndDogsLivingTogether()
catch error
  print error
finally
  cleanUp()

Chained Comparisons

cholesterol값이 200보다 작거나 60보다 큰지 검사합니다.

example-30.coffee
1
2
3
cholesterol = 127

healthy = 200 > cholesterol > 60

String Interpolation, Block Strings, and Block Comments

#{}은 문자열 보간입니다. #{ number / number}사용시 문자로 취급합니다.

example-31.coffee
1
2
3
4
quthor = "Wittgenstein"
quote  = "A picture is a fact. -- #{ author }"

sentence = "#{ 22/ 7 } is a decent approximation of ㅠ"

coffeescript 는 여러 문장의 개행을 인식 하지 않습니다.

example.32
1
2
3
4
5
6
mobyDick = "Call me Ishmael. Some years ago --
  never mind how long precisely -- having little
  or no money in my purse, and nothing particular
  to interset me on shore, I thought I would sail
  about a little and see the watery part of the
  world…"

Javascript 변환시 개행문자를 추가 하려면 """사용해 주어야 합니다.

example-33.coffee
1
2
3
4
5
html = """
  <strong>
    cup of coffeescript
  </strong>
  """

coffeescript의 여러줄 주석 입니다.

example-34.coffee
1
2
3
4
###
CoffeeScript Compiler v1.4.0
Released under the MIT License
###

Block Regular Expressions

OPERATOR = /// ^ (
  ?:[-=]>
   | [-+*/%<>&|^!?=]=
   | >>>=?
   |([-+:])\1
   |([&|<>])\2=?
   |\?\.
   |\.{2,3}
) ///

CoffeeScript Style Guide

CoffeeScript의 문법 사용법을 알려주는 사이트 주소 입니다. CoffeeScript Style Guide

Comments