Skip to content

Commit a6704bd

Browse files
committedAug 25, 2024·
feat(linter/unicorn): add fixer to prefer-set-size (#5149)
1 parent 67c7802 commit a6704bd

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed
 

‎crates/oxc_linter/src/rules/unicorn/prefer_set_size.rs

+28-5
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ use oxc_diagnostics::OxcDiagnostic;
66
use oxc_macros::declare_oxc_lint;
77
use oxc_span::Span;
88

9-
use crate::{ast_util::get_declaration_of_variable, context::LintContext, rule::Rule, AstNode};
9+
use crate::{
10+
ast_util::get_declaration_of_variable, context::LintContext, fixer::Fix, rule::Rule, AstNode,
11+
};
1012

1113
fn prefer_set_size_diagnostic(span0: Span) -> OxcDiagnostic {
1214
OxcDiagnostic::warn(
@@ -38,7 +40,7 @@ declare_oxc_lint!(
3840
/// ```
3941
PreferSetSize,
4042
correctness,
41-
pending
43+
fix
4244
);
4345

4446
impl Rule for PreferSetSize {
@@ -68,13 +70,22 @@ impl Rule for PreferSetSize {
6870
return;
6971
};
7072

71-
let maybe_set = &spread_element.argument.without_parenthesized();
73+
let maybe_set = &spread_element.argument.get_inner_expression();
7274

7375
if !is_set(maybe_set, ctx) {
7476
return;
7577
}
7678

77-
ctx.diagnostic(prefer_set_size_diagnostic(span));
79+
ctx.diagnostic_with_fix(prefer_set_size_diagnostic(span), |_fixer| {
80+
vec![
81+
// remove [...
82+
Fix::delete(Span::new(array_expr.span.start, spread_element.span.start + 3)),
83+
// remove everything after the end of the spread element (including the `]` )
84+
Fix::delete(Span::new(spread_element.span.end, array_expr.span.end)),
85+
// replace .length with .size
86+
Fix::new("size", span),
87+
]
88+
});
7889
}
7990
}
8091

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

160-
Tester::new(PreferSetSize::NAME, pass, fail).test_and_snapshot();
171+
let fix = vec![
172+
(r"[...new Set(array)].length", r"new Set(array).size"),
173+
(r"[...new Set(array),].length", r"new Set(array).size"),
174+
(r"[...(( new Set(array) ))].length", r"(( new Set(array) )).size"),
175+
(r"[...(( new Set(array as foo) ))].length", r"(( new Set(array as foo) )).size"),
176+
(r"[...(( new Set(array) as foo ))].length", r"(( new Set(array) as foo )).size"),
177+
(
178+
r"[...(( new Set(array) as foo ) ) ] .length;",
179+
r"(( new Set(array) as foo ) ) .size;",
180+
),
181+
];
182+
183+
Tester::new(PreferSetSize::NAME, pass, fail).expect_fix(fix).test_and_snapshot();
161184
}

0 commit comments

Comments
 (0)
Please sign in to comment.