🚀 Feature: Find or create a lint rule to prefer inverting a single 'if' to reduce nesting
Bug Report Checklist
- [X] I have tried restarting my IDE and the issue persists.
- [X] I have pulled the latest
mainbranch of the repository. - [X] I have searched for related issues and found none that matched my issue.
Overview
I often see functions like:
function doSomething() {
if (someCondition) {
const someOtherValue = getSomething();
doSomethingWithSomeOtherValue();
}
}
If a function consists entirely of an if and that if contains a declaration, I'd generally consider it cleaner to instead invert the if to reduce nesting:
function doSomething() {
if (!someCondition) {
return;
}
const someOtherValue = getSomething();
doSomethingWithSomeOtherValue();
}
Let's find or create an ESLint plugin to do this.
Additional Info
https://stackoverflow.com/questions/268132/invert-if-statement-to-reduce-nesting goes into the reasoning for this nicely.
This was proposed to ESLint in https://github.com/eslint/eslint/issues/10120 but never ratified.
I am quite interested in this
@regru/eslint-plugin-prefer-early-return provides this rule (the ESLint config I use includes it, I've found it to be quite handy).
I like to think that libraries would be keen on this rule (I'm so sorry)
I like to think that libraries would be keen on this rule (I'm so sorry)
I don't understand. What are you trying to say? I interpret this as meaning that "libraries would find that rule more helpful, so it doesn't make sense for this template", but I doubt that's what you meant. Can you clarify? 🙃