26
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

応用的なCoffeeScriptの書き方を覚えたら、きっと昨日よりもモテるよね?ね?

Last updated at Posted at 2013-04-11

いつまでたってもイージーな書き方しかできないから、ちゃんとします。
サンプルは公式から取ってきた
http://coffeescript.org/

一行でObjectを書いちゃう

$('.account').attr class: 'active'

yearsOld = max: 10, ida: 9, tim: 11

$('.account').attr({
  "class": 'active'
});

yearsOld = {
  max: 10,
  ida: 9,
  tim: 11
};

読みにくいけど三項演算子ほしい

date = if friday then sue else jill

date = friday ? sue : jill;

じゃっかん読みにくいけど、三項演算子つかいたい。

forまわり

一行でforする

foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'

一行でforして配列ゲットする

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

とか

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

byなんてやつがある

evens = (x for x in [0..10] by 2)

黒魔術にしか見えないRangeをつかおう

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

start   = numbers[0..2]
middle  = numbers[3...6]
end     = numbers[6..]
copy    = numbers[..]
numbers[3..6] = [-3, -4, -5, -6]

存在演算子

http://coffeescript.org/#operators
↑ここの下の方 The Existential Operator

speed ?= 15 #speedがなかったら15が入る

footprints = yeti ? "bear" #yetiがなかったら'bear'が入る

zip = lottery.drawWinner?().address?.zipcode

prototypeに追加

String::dasherize = ->
  this.replace /_/g, "-"

String.prototype.dasherize = function() {
  return this.replace(/_/g, "-");
};

Objectから抜き出すやつ(なんて名前?nodeでよく{exec}とかでみかけるやつ)

http://coffeescript.org/#destructuring
↑ここの5つめくらい

class Person
  constructor: (options) -> 
    {@name, @age, @height} = options

Person = (function() {
  function Person(options) {
    this.name = options.name, this.age = 	options.age, this.height = options.height;
  }

Switchで初期化

score = 76
grade = switch
  when score < 60 then 'F'
  when score < 70 then 'D'
  when score < 80 then 'C'
  when score < 90 then 'B'
  else 'A'
# grade == 'C'

Chained Comparisons

cholesterol = 127
healthy = 200 > cholesterol > 60 # true

doでクロージャをつくろう

(よくわかってない)

逆にこの応用はつかわないよ

読みにくいので使わない

  • unless ←個人的に直感的でない
  • 後置のif ← 単純に読みにくい。「えっ。この行、このタイミングで条件付き?ガチで?」ってなる。

どこで使うのか検討がつかない

Destructuring Assignment

theBait   = 1000
theSwitch = 0

[theBait, theSwitch] = [theSwitch, theBait]

これで完璧!今日から、ドヤ顔してモテよう!

スタバでドヤリングしてCoffeeでも飲もう!

image

26
26
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?