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 1 year has passed since last update.

function 引数を Object とし各プロパティのデフォルト値を個別に宣言する

Last updated at Posted at 2022-10-14

要件

  • function の引数を Object 化
  • 引数のデフォルト値を指定したい
  • Objectの property を個別に default 化したい

結論

sample.js
// default 値 を纏めた Object
const DEFAULT_ARGS = {
  name: "hoge",
  value: "fuga",
  flag: true,
}

// 引数の default 値を Object に指定
module.exports = ( args = DEFAULT_ARGS ) => {
  // default <= args 方向に差分をコピーする
  args = {
    ...DEFAULT_ARGS,
    ...args,
  }

  return args
}

使用例

expample.js
const sample = require("./sample.js");

let args;

// 引数なし
args = sample();
console.log(args.name, args.value, args.flag); //-> hoge, fuga, true

// 引数 空オブジェクト
args = sample({});
console.log(args.name, args.value, args.flag); //-> hoge, fuga, true

// 引数 オブジェクトのプロパティを1つ指定
args = sample({name: "aaa"});
console.log(args.name, args.value, args.flag); //-> aaa, fuga, true

// 引数 オブジェクトのプロパティを2つ指定
args = sample({name: "aaa", value: "bbb"});
console.log(args.name, args.value, args.flag); //-> aaa, bbb, true

// 引数 オブジェクトのプロパティを3つ指定
args = sample({name: "aaa", value: "bbb", flag: false});
console.log(args.name, args.value, args.flag); //-> aaa, bbb, false

以上

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