0
0

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 3 years have passed since last update.

JavaScriptの関数をRubyっぽくする

Last updated at Posted at 2021-08-12

##したいこと

  • 引数をオブジェクトで渡す
  • 引数のデフォルト値を定める
  • 関数側でキーを変数として定める

##Ruby
関数を定義するときrubyだと

def func(a: 1, b: 2)
 p a, b
end

func(a: 2) #=> [2, 2]

みたいにできて便利

##JavaScript
これと同じことをJSでやろうとすると

let func = (options) => {
  let a = options.a === undefined ? 1 : options.a;
  let b = options.b === undefined ? 2 : options.b;
  console.log(a, b);
}

func({a: 2}) //> 2, 2

のようになり冗長。

##結論
これをDRYにすると

@shiracamusさんからコメントいただきました。普通に同じキーを後に付け加えれば上書きできるんですね。その発想はなかったです。ありがとうございます。

let func = (options) => {
//  let {a, b} = Object.assign({
//    a: 1,
//    b: 2
//  }, options)
  let {a, b} = {a: 1, b: 2, ...options}
  console.log(a, b)
}

func({a: 2}) //> 2, 2
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?