Skip to content

Commit

Permalink
fix(linter): explicit-length-check inside ternary
Browse files Browse the repository at this point in the history
  • Loading branch information
maurice committed Jan 18, 2024
1 parent 3d184d5 commit 4b66568
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
5 changes: 5 additions & 0 deletions crates/oxc_linter/src/rules/unicorn/explicit_length_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,8 @@ fn test() {
// need getStaticValue
// ("const A_NUMBER = 2; const x = foo.length || A_NUMBER", None),
("class A { a(){ if(this.length); while(!this.size || foo);}}", None),
// Use of .size but not in conditional "test" position
("const totalCount = tests.reduce((count, test) => count + (test.enabled ? test.maxSize : test.size), 0)", None),
];

let fail = vec![
Expand All @@ -361,7 +363,10 @@ fn test() {
("const x = foo.length || bar()", None),
("() => foo.length && bar()", None),
("alert(foo.length && bar())", None),
// Use of .size in conditional "test" position
("let foo = arr.length ? 'non-empty' : 'empty'", None),
];

let fixes = vec![
(
r"if ( !!!( !foo.length && foo.length == 0 && foo.length < 1 && 0 === foo.length && 0 == foo.length && 1 > foo.length ) ||
Expand Down
6 changes: 6 additions & 0 deletions crates/oxc_linter/src/snapshots/explicit_length_check.snap
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,10 @@ expression: explicit_length_check
╰────
help: Replace `.length` with `.length > 0`.

eslint-plugin-unicorn(explicit-length-check): Use `.length > 0` when checking length is not zero.
╭─[explicit_length_check.tsx:1:1]
1let foo = arr.length ? 'non-empty' : 'empty'
· ──────────
╰────


12 changes: 10 additions & 2 deletions crates/oxc_linter/src/utils/unicorn/boolean.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use oxc_ast::{
ast::{CallExpression, Expression},
ast::{CallExpression, ConditionalExpression, Expression},
AstKind,
};
use oxc_semantic::AstNode;
use oxc_span::GetSpan;
use oxc_syntax::operator::UnaryOperator;

use crate::{ast_util::outermost_paren_parent, LintContext};
Expand Down Expand Up @@ -48,14 +49,21 @@ pub fn is_boolean_node<'a, 'b>(node: &'b AstNode<'a>, ctx: &'b LintContext<'a>)
if matches!(
parent.kind(),
AstKind::IfStatement(_)
| AstKind::ConditionalExpression(_)
| AstKind::WhileStatement(_)
| AstKind::DoWhileStatement(_)
| AstKind::ForStatement(_)
) {
return true;
}

if let AstKind::ConditionalExpression(ConditionalExpression {
test: conditional_test, ..
}) = parent.kind()
{
let expr_span = conditional_test.get_inner_expression().without_parenthesized().span();
return expr_span == node.kind().span();
}

if is_logical_expression(parent) {
return is_boolean_node(parent, ctx);
}
Expand Down

0 comments on commit 4b66568

Please sign in to comment.