'How to grab JavaScript destructured parameters independent of variable name?
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?
Solution 1:[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 });
}
Solution 2:[2]
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)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
| Solution 2 | BlueWater86 |
