0

Wish to enact upon arguments but with defaults defined

In my quest for self-documenting code with destructuring but being DRY wanting to do this...

async function shampoo({ lather = true, rinse = true, repeat = 2 } = {}) {
  await api.dogWasherMachine(magicalArguments) // ???
  // don't want to have to do this:
  // api.dogWasherMachine({ lather, rinse, repeat })
  // currenty arguments is {} and actual input is defined
}

How do I get these magical arguments that are defined?

arguments do not have the default input defined but how can I do this?

King Friday
  • 25,132
  • 12
  • 90
  • 84

2 Answers2

1

It's not possible to do it in the parameters alone - destructuring necessarily extracts each property into an independent named variable, without leaving a reference to the original object behind. You'll have to do it with another statement, eg:

async function shampoo(param = {}) {
  const defaultObj = {
    lather: true,
    rinse: true,
    repeat: 2
  };
  await api.dogWasherMachine({ ...defaultObj, ...param });
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

I use destructuring assignment to to self document inheritable classes that are used as interfaces. On construction I get all of the benefits of intellisense and when calling an API everything stays nice and DRY.

class washable {
  constructor({ lather = true, rinse = true, repeat = 2 } = {}) {
    this.lather = lather
    this.rinse = rinse
    this.repeat = repeat
  }
}

class dog extends washable {
  async shampoo() {
     await api.dogWasherMachine(this)
  }
}
BlueWater86
  • 1,773
  • 12
  • 22
  • but... count the number of times you wrote "repeat". – King Friday Jun 27 '19 at 01:11
  • Agreed but without destructing assignment in your function call (like in your question) how is the function self documenting to external code? – BlueWater86 Jun 27 '19 at 01:16
  • Yah you are right and thanks for the answer. I would probably use TypeScript in that case. – King Friday Jun 27 '19 at 01:21
  • I assume by TypeScript you mean JSDoc definitions? Personally I would like to see the ability to destructure directly onto an instance through a class method similar to the answer [here](https://stackoverflow.com/a/40624564/3236706) – BlueWater86 Jun 27 '19 at 01:30