LoginSignup
7
7

More than 5 years have passed since last update.

オブジェクトのプロパティをオブジェクトで設定する関数

Posted at

tatyusa/n_puzzle を作っててオブジェクトのプロパティの設定にいちいち

text.x = 40
text.y = 140
text.size = 64
text.bold = true
text.underline = true
text.color = "yellow"
text.rotation = -20

こんなことをするのがだるくなってきた話。

※コードは全てCoffeeScriptで書いています

オブジェクト名を何度も打つのは冗長だし他にもオブジェクトがあった時に使いまわせる設定があったら使いまわしたい。
そこでこんな関数を考えてみた

allocate = (obj, configs...) ->
  for config in configs
    for key, value of config
      obj[key] = value

これだと冒頭のコードはこんな風に書ける

allocate text,
  x: 40
  y: 140
  size: 64
  bold: true
  underline: true
  color: "yellow"
  rotation: -20

オブジェクト名の記述は一回で住むし何よりオブジェクトで管理してるから使い回しが簡単!
例えば以下の通りである

default =
  x: 0
  y: 20

allocate text0,
  default,
  alpha: 0

allocate text1,
  default,
  alpha: 1

これは便利そう
実際に使ったらこんな感じに書き換わった

7
7
0

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