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
28 changes: 23 additions & 5 deletions crates/oxc_linter/src/rules/unicorn/no_useless_spread/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ declare_oxc_lint!(
/// ```
NoUselessSpread,
correctness,
conditional_fix
fix_dangerous
);

impl Rule for NoUselessSpread {
Expand Down Expand Up @@ -380,26 +380,43 @@ fn check_useless_clone<'a>(
is_array: bool,
spread_elem: &SpreadElement<'a>,
ctx: &LintContext<'a>,
) -> bool {
) {
let span = Span::new(spread_elem.span.start, spread_elem.span.start + 3);
let target = spread_elem.argument.get_inner_expression();

// already diagnosed by first check
if matches!(target, Expression::ArrayExpression(_) | Expression::ObjectExpression(_)) {
return false;
return;
}

let hint = target.const_eval();
let hint_matches_expr = if is_array { hint.is_array() } else { hint.is_object() };
if hint_matches_expr {
let name = diagnostic_name(ctx, target);

// `[...new Array(1)]` -> `new Array(1).fill()`
if let Expression::NewExpression(new_expr) = target {
let is_array_constructor = new_expr
.callee
.without_parentheses()
.get_identifier_reference()
.is_some_and(|id| id.name == "Array");

if is_array_constructor && new_expr.arguments.len() == 1 {
ctx.diagnostic_with_fix(clone(span, is_array, name), |fixer| {
fixer.replace(
array_or_obj_span,
format!("{}.fill()", fixer.source_range(spread_elem.argument.span())),
)
});
return;
}
}

ctx.diagnostic_with_fix(clone(span, is_array, name), |fixer| {
fix_by_removing_array_spread(fixer, &array_or_obj_span, spread_elem)
});
return true;
}
false
}

fn diagnostic_name<'a>(ctx: &LintContext<'a>, expr: &Expression<'a>) -> Option<&'a str> {
Expand Down Expand Up @@ -725,6 +742,7 @@ fn test() {
// useless clones - simple arrays
("[...foo.map(x => !!x)]", "foo.map(x => !!x)"),
("[...new Array()]", "new Array()"),
("[...new Array(3)]", "new Array(3).fill()"),
("[...new Array(1, 2, 3)]", "new Array(1, 2, 3)"),
// useless clones - complex
(r"[...await Promise.all(foo)]", r"await Promise.all(foo)"),
Expand Down