Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
}