LoginSignup
2
2

More than 5 years have passed since last update.

CoffeeScriptでfilter&mapをforに置き換える

Posted at

CoffeeScriptでfilterとmapを併用するケースは、forに置き換えることができる。
↓は配列の中身を全てtrimして、undefined・null・空文字のものを取り除いた配列を生成する関数の例。

trim_all.coffee
# (1) filter and map version.
trim_all = (ary) -> ary.filter((e) -> e?.trim()).map (e) -> e.trim() 

# (2) for version.
trim_all = (ary) -> e.trim() for e in ary when e?.trim()

# (3) for version 2.
trim_all = (ary) -> t for e in ary when t = e?.trim()

(1)はfilter・mapのそれぞれでループするため、ループが2回になっている。
(2)のfor版だとループが1回で済む。
更にforだとスコープが同じなため、(3)のようにwhenの計算結果を再利用することも可能。
 Note: (1)ではfilterに渡す関数とmapに渡す関数のスコープが違うため、エラーとなる。

2
2
2

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
2
2