Skip to content

Commit

Permalink
feat(linter) add fixer to prefer-date-now
Browse files Browse the repository at this point in the history
  • Loading branch information
camc314 committed Aug 23, 2024
1 parent 7eb052e commit 3abd301
Showing 1 changed file with 23 additions and 10 deletions.
33 changes: 23 additions & 10 deletions crates/oxc_linter/src/rules/unicorn/prefer_date_now.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ declare_oxc_lint!(
/// ```
PreferDateNow,
pedantic,
pending
fix
);

impl Rule for PreferDateNow {
Expand All @@ -67,10 +67,13 @@ impl Rule for PreferDateNow {
&& matches!(member_expr.static_property_name(), Some("getTime" | "valueOf"))
&& is_new_date(member_expr.object().without_parenthesized())
{
ctx.diagnostic(prefer_date_now_over_methods(
call_expr.span,
member_expr.static_property_name().unwrap(),
));
ctx.diagnostic_with_fix(
prefer_date_now_over_methods(
call_expr.span,
member_expr.static_property_name().unwrap(),
),
|fixer| fixer.replace(call_expr.span, "Date.now()"),
);
}
}

Expand All @@ -83,9 +86,10 @@ impl Rule for PreferDateNow {
call_expr.arguments.first().and_then(Argument::as_expression)
{
if is_new_date(expr.without_parenthesized()) {
ctx.diagnostic(prefer_date_now_over_number_date_object(
call_expr.span,
));
ctx.diagnostic_with_fix(
prefer_date_now_over_number_date_object(call_expr.span),
|fixer| fixer.replace(call_expr.span, "Date.now()"),
);
}
}
}
Expand All @@ -99,7 +103,9 @@ impl Rule for PreferDateNow {
return;
}
if is_new_date(&unary_expr.argument) {
ctx.diagnostic(prefer_date_now(unary_expr.argument.span()));
ctx.diagnostic_with_fix(prefer_date_now(unary_expr.argument.span()), |fixer| {
fixer.replace(unary_expr.span, "Date.now()")
});
}
}
AstKind::AssignmentExpression(assignment_expr) => {
Expand Down Expand Up @@ -217,5 +223,12 @@ fn test() {
r"function foo(){return-new Date}",
];

Tester::new(PreferDateNow::NAME, pass, fail).test_and_snapshot();
let fix = vec![
("new Date().getTime()", "Date.now()"),
("new Date().valueOf()", "Date.now()"),
("Number(new Date())", "Date.now()"),
("BigInt(new Date())", "Date.now()"),
];

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

0 comments on commit 3abd301

Please sign in to comment.