Skip to content

Commit

Permalink
feat(linter/unicorn): add fixer to prefer-set-size (#5149)
Browse files Browse the repository at this point in the history
  • Loading branch information
camc314 committed Aug 25, 2024
1 parent 67c7802 commit a6704bd
Showing 1 changed file with 28 additions and 5 deletions.
33 changes: 28 additions & 5 deletions crates/oxc_linter/src/rules/unicorn/prefer_set_size.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;

use crate::{ast_util::get_declaration_of_variable, context::LintContext, rule::Rule, AstNode};
use crate::{
ast_util::get_declaration_of_variable, context::LintContext, fixer::Fix, rule::Rule, AstNode,
};

fn prefer_set_size_diagnostic(span0: Span) -> OxcDiagnostic {
OxcDiagnostic::warn(
Expand Down Expand Up @@ -38,7 +40,7 @@ declare_oxc_lint!(
/// ```
PreferSetSize,
correctness,
pending
fix
);

impl Rule for PreferSetSize {
Expand Down Expand Up @@ -68,13 +70,22 @@ impl Rule for PreferSetSize {
return;
};

let maybe_set = &spread_element.argument.without_parenthesized();
let maybe_set = &spread_element.argument.get_inner_expression();

if !is_set(maybe_set, ctx) {
return;
}

ctx.diagnostic(prefer_set_size_diagnostic(span));
ctx.diagnostic_with_fix(prefer_set_size_diagnostic(span), |_fixer| {
vec![
// remove [...
Fix::delete(Span::new(array_expr.span.start, spread_element.span.start + 3)),
// remove everything after the end of the spread element (including the `]` )
Fix::delete(Span::new(spread_element.span.end, array_expr.span.end)),
// replace .length with .size
Fix::new("size", span),
]
});
}
}

Expand Down Expand Up @@ -157,5 +168,17 @@ fn test() {
r"[...new /* comment */ Set(array)].length",
];

Tester::new(PreferSetSize::NAME, pass, fail).test_and_snapshot();
let fix = vec![
(r"[...new Set(array)].length", r"new Set(array).size"),
(r"[...new Set(array),].length", r"new Set(array).size"),
(r"[...(( new Set(array) ))].length", r"(( new Set(array) )).size"),
(r"[...(( new Set(array as foo) ))].length", r"(( new Set(array as foo) )).size"),
(r"[...(( new Set(array) as foo ))].length", r"(( new Set(array) as foo )).size"),
(
r"[...(( new Set(array) as foo ) ) ] .length;",
r"(( new Set(array) as foo ) ) .size;",
),
];

Tester::new(PreferSetSize::NAME, pass, fail).expect_fix(fix).test_and_snapshot();
}

0 comments on commit a6704bd

Please sign in to comment.