eslint-plugin-unicorn
eslint-plugin-unicorn copied to clipboard
Rule proposal: a-implies-b
Description
When comparing strict equality of two entries and that another condition must be true for one of the conditions, I often see that both conditions are checked individually again. Instead, recommending to just do that once would be great to minimize code and prevent the CPU cycles calculating the extra equality.
Examples
Fail ❌
// In any order
a > 0 && b > 0 && a === b
a > 0 && b > 2 && a === b
a < c && b < c && a === b
a !== 'test' && b !== 'test' && a === b
a === 'test' && b === 'test' && a === b
a === 'test' && b !== 'test' && a !== b
a !== 'test' && b === 'test' && a !== b
Pass ✅
a > 0 && a === b
// a > 0 && b > 2 && a === b
b > 2 && a === b
a < c && a === b
a !== 'test' && a === b
a === 'test' && a === b
a === 'test' && a !== b
// a !== 'test' && b === 'test' && a !== b
b === 'test' && a !== b
Proposed rule name
a-implies-b
Additional Info
This would not be auto-fixable, since objects could for example have a toPrimitive symbol attached that has a dynamic outcome.
This is generic boolean algebra and it could cover a variety of situations. Biome has something similar: https://biomejs.dev/linter/rules/use-simplified-logic-expression/
I also found this: https://github.com/azat-io/eslint-plugin-de-morgan
As for the specific example I think it's too niche
I absolutely agree that it could cover a variety of situations and that the example is just some part.
I do believe it would be valuable to just start with some cases and add more over time, since the implementation could be more tricky to. The mentioned related rules are also good, while they don't cover the case I mentioned here.