πPutout plugin adds ability to transform logical expressions
npm install @putout/plugin-logical-expressions[NPMIMGURL]: https://img.shields.io/npm/v/@putout/plugin-logical-expressions.svg?style=flat&longCache=true
[NPMURL]: https://npmjs.org/package/@putout/plugin-logical-expressions "npm"
> The logical NOT (!) operator takes truth to falsity and vice versa.
>
> (c) MDN
πPutout plugin adds ability to simplify logical expressions containing
comparisons which will always evaluate to true or false since it's likely indications of programmer error.
Complements @putout/plugin-apply-comparison-order.
```
npm i @putout/plugin-logical-expressions -D
- β
convert-bitwise-to-logical;
- β
remove-boolean;
- β
remove-duplicates;
- β
simplify;
`json`
{
"rules": {
"logical-expressions/simplify": "on",
"logical-expressions/remove-boolean": "on",
"logical-expressions/remove-duplicates": "on",
"logical-expressions/convert-bitwise-to-logical": "on"
}
}
`js
const is = !(options && !options.bidirectional);
if (!left.type === 'UnaryExpression') {}
const oneOf = a || a;
const same = a === a;
a() && b;
`
`js
const is = !options || options.bidirectional;
if (left.type !== 'UnaryExpression') {}
const oneOf = a;
const same = true;
a();
`
The rule also simplify duplication use:
`diff`
-if (a && b || a && c) {
+if (a && (b || c)) {
}
Wrong cases with instanceof:
`diff`
-!a instanceof b;
-a instanceof !b;
-!a instanceof !b;
+!(a instanceof b);
Wrong cases with in:
`diff`
-!a in b;
-a in !b;
+!(a in b);
In case of duplicates:
`diff`
-a && b && a
+a && b
> A boolean is a logical data type that can have only the values true or false.
>
> (c) MDN
`js`
const t = true && false;
`js`
const t = false;
`js`
const t = a && b && a;
`js`
const t = a && b;
> The bitwise OR operator (|) returns a 1 in each bit position for which the corresponding bits of either or both operands are 1s.
>
> The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones).
>
> (c) MDN
Convert bitwise to logical operator, when one of operands is not a number, since mostly likely it is an error.
`js
a | !b;
if (!(a !== b))
fn();
`
`js
a || !b;
if (a === b)
fn();
`
Linter | Rule | Fix
--------|-------|------------|
π Putout| logical-expressions| β
β£ ESLint | no-constant-binary-expression` | β
MIT