From db6558f33c90469002343918fa82787441299c49 Mon Sep 17 00:00:00 2001 From: dalaoshu Date: Mon, 25 Nov 2024 16:32:48 +0800 Subject: [PATCH] fix(linter): false positive in `eslint/prefer-object-has-own` (#7463) closes #7450 --- .../src/rules/eslint/prefer_object_has_own.rs | 25 ++++++++----------- .../src/snapshots/prefer_object_has_own.snap | 7 ++++++ 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/crates/oxc_linter/src/rules/eslint/prefer_object_has_own.rs b/crates/oxc_linter/src/rules/eslint/prefer_object_has_own.rs index cc4b4f0cc8467..a2c921c89edc9 100644 --- a/crates/oxc_linter/src/rules/eslint/prefer_object_has_own.rs +++ b/crates/oxc_linter/src/rules/eslint/prefer_object_has_own.rs @@ -87,21 +87,12 @@ impl Rule for PreferObjectHasOwn { ctx.diagnostic(diagnostic); } else { ctx.diagnostic_with_fix(diagnostic, |fixer| { - let before_token_of_replace_span = if replace_target_span.start > 1 { - Some(ctx.source_range(Span::new( - replace_target_span.start - 1, - replace_target_span.start, - ))) - } else { - None - }; - let replacement = match before_token_of_replace_span { - Some(token) => match token { - " " | "=" | "/" | "(" => "Object.hasOwn", - _ => " Object.hasOwn", - }, - _ => "Object.hasOwn", - }; + let needs_space = replace_target_span.start > 1 + && !ctx + .source_range(Span::new(0, replace_target_span.start)) + .ends_with(&[' ', '=', '/', '(']); + + let replacement = if needs_space { " Object.hasOwn" } else { "Object.hasOwn" }; fixer.replace(replace_target_span, replacement) }); } @@ -238,6 +229,8 @@ fn test() { "Object[`hasOwnProperty`][`call`](object, property);", "({})['hasOwnProperty']['call'](object, property);", "({})[`hasOwnProperty`][`call`](object, property);", + // Issue: + "…Object.prototype.hasOwnProperty.call(C,x);", ]; let fix = vec![ @@ -385,6 +378,8 @@ fn test() { "Object.hasOwn(object, property);", None, ), + // Issue: + ("…Object.prototype.hasOwnProperty.call(C,x);", "… Object.hasOwn(C,x);", None), ]; Tester::new(PreferObjectHasOwn::NAME, pass, fail).expect_fix(fix).test_and_snapshot(); } diff --git a/crates/oxc_linter/src/snapshots/prefer_object_has_own.snap b/crates/oxc_linter/src/snapshots/prefer_object_has_own.snap index 76765aa108d4e..db5c341551455 100644 --- a/crates/oxc_linter/src/snapshots/prefer_object_has_own.snap +++ b/crates/oxc_linter/src/snapshots/prefer_object_has_own.snap @@ -231,3 +231,10 @@ snapshot_kind: text · ──────────────────────────────────────────────── ╰──── help: Replace `({})[`hasOwnProperty`][`call`]` with `Object.hasOwn`. + + ⚠ eslint(prefer-object-has-own): Disallow use of `Object.prototype.hasOwnProperty.call()` and prefer use of `Object.hasOwn()`. + ╭─[prefer_object_has_own.tsx:1:3] + 1 │ …Object.prototype.hasOwnProperty.call(C,x); + · ───────────────────────────────────────── + ╰──── + help: Replace `Object.prototype.hasOwnProperty.call` with ` Object.hasOwn`.