LoginSignup
37

More than 5 years have passed since last update.

coffeescript ワンライナー(一行)集

Last updated at Posted at 2014-02-13

coffeescriptのワンライナー記法(一部)をまとめました。

setTimeout

CoffeeScript
setTimeout (-> console.log('hoge')), 1000
JavaScript
setTimeout((function() {
  return console.log('hoge');
}), 1000);

if

CoffeeScript
console.log 'hoge' if true
JavaScript
if (true) {
  console.log('hoge');
}

三項演算子

CoffeeScript
hoge =  if bool then 'true' else 'false'
JavaScript
hoge = bool ? 'true' : 'false';

function

CoffeeScript
fn = (x) -> x * x
JavaScript
fn = function(x) {
  return x * x;
};

即時関数

CoffeeScript
do ($ = jQuery) ->
JavaScript
(function($) {})(jQuery); 
CoffeeScript
do tick = ->
JavaScript
(tick = function() {})();

Object

CoffeeScript
obj = port: 8008, hostname: '0.0.0.0'
JavaScript
obj = {
  port: 8008,
  hostname: '0.0.0.0'
};

一括Object変数

CoffeeScript
{@x, @y, @z} = args
JavaScript
this.x = args.x, this.y = args.y, this.z = args.z;

一括Array変数

CoffeeScript
[x, y, z] = args
JavaScript
x = args[0], y = args[1], z = args[2];

一括変数定義

CoffeeScript
[x, y, z] = [1, 2, 3]
JavaScript
_ref = [1, 2, 3], x = _ref[0], y = _ref[1], z = _ref[2];

Array range

CoffeeScript
arr = [0...4]
JavaScript
arr = [0, 1, 2, 3];

apply

CoffeeScript
$.when deferreds...
JavaScript
$.when.apply($, deferreds);   

他にもリスト内包表記などがありますが、今回は割愛します。

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
37