Skip to content

Commit

Permalink
feat(linter) add fixer to prefer-set-size
Browse files Browse the repository at this point in the history
  • Loading branch information
camc314 committed Aug 23, 2024
1 parent 7eb052e commit 501fc36
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 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 @@ -74,7 +76,16 @@ impl Rule for PreferSetSize {
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,11 @@ 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"),
];

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

0 comments on commit 501fc36

Please sign in to comment.