prefer-destructuring - Option to skip when destructurable variables count less than N
See original GitHub issueWhat rule do you want to change? prefer-destructuring
Does this change cause the rule to produce more or fewer warnings? Fewer
How will the change be implemented? (New option, new default behavior, etc.)? New option (Not sure if it should have some non-zero default value)
Please provide some example code that this change will affect:
const abc = this.state.abc;
// other non-assignment stuff
What does the rule currently do for this code? Asks to convert to destructuring syntax, even if there is only one destructurable variable.
const {abc} = this.state;
// other non-assignment stuff
What will the rule do after it’s changed? Keep it unchanged, for upto N allowed destructurable variables. (makes most sense when N = 1)
Reasoning behind the suggestion:
We use lot of code like this
// Unfixed
const abc = this.state.abc;
// Fixed
const { abc } = this.state;
To me it doesn’t make much sense to use destructuring just for one variables like this. First one is much more explicit without being repetitive (which is the case for multiple sequential assignments like shown below).
The rule definitely makes sense for multiple assignments like this -
const a = this.state.a;
const b = this.state.b;
const c = this.state.c;
because the fixed code is concise and clear -
const { a, b, c } = this.state;
but for one variable, its hardly concise and looks too complex when it isn’t.
Although it makes more sense to me to skip 1 variable situation, but we should probably keep it configurable as N.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:9 (3 by maintainers)
Top GitHub Comments
Added some thoughts on already destructured variables in https://github.com/eslint/eslint/issues/10743#issuecomment-415186659
Would be nice to hear more thoughts on this and take a call on whether this should be added to core.
From what I can think of, there are two ways to count the number of possible destructurings (dest count) for a variable:
Ex :
Say, with min destructuring count of 3 (config),
this would raise warning:
this will not raise warning:
Say, with min destructuring count of 3 (config),
this would raise warning:
this will not raise warning:
I prefer the 2nd approach as it is more permissive (in terms of counting).
Added later:
Already destructured variables should also add to the count in a different way. For eg, with this sample:
To-be Destructured count (earlier called dest count) for
data
[ToBeCount
] = 2 Already Destructured count fordata
= 1 Total (To-be + Already) destructured count fordata
[TotalCount
] = 3Condition to raise error is
(TotalCount > MinCount) && ToBeCount > 0
(Plugin option isMinCount
)Now, given various
MinCount
, this is how previous snippet will work:A. MinCount = 1 Raise error for both assignments in line 2
B. MinCount = 2 Raise error for both assignments in line 2
C. MinCount = 3 No error