Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid unnecessary optional chaining in autofix for no-get rule when using useOptionalChaining option #1286

Merged
merged 1 commit into from
Aug 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 5 additions & 1 deletion lib/rules/no-get.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,12 @@ function fixGet({
return null;
}

const getResultIsChained = node.parent.type === 'MemberExpression' && node.parent.object === node;

// If the result of get is chained, we can safely autofix nests paths without using optional chaining.
// In the left side of an assignment, we can safely autofix nested paths without using optional chaining.
let replacementPath = isInLeftSideOfAssignmentExpression ? path : path.replace(/\./g, '?.');
let replacementPath =
getResultIsChained || isInLeftSideOfAssignmentExpression ? path : path.replace(/\./g, '?.');

// Replace any array element access (foo.1 => foo[1] or foo?.[1]).
replacementPath = replacementPath
Expand Down
29 changes: 29 additions & 0 deletions tests/lib/rules/no-get.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,24 @@ ruleTester.run('no-get', rule, {
options: [{ catchUnsafeObjects: true }],
errors: [{ message: ERROR_MESSAGE_GET, type: 'CallExpression' }],
},
{
code: "foo1.foo2.get('bar').baz;",
output: 'foo1.foo2.bar.baz;',
options: [{ catchUnsafeObjects: true, useOptionalChaining: true }],
errors: [{ message: ERROR_MESSAGE_GET, type: 'CallExpression' }],
},
{
code: "foo1.foo2.get('bar.bar').baz;",
output: null,
options: [{ catchUnsafeObjects: true }],
errors: [{ message: ERROR_MESSAGE_GET, type: 'CallExpression' }],
},
{
code: "foo1.foo2.get('bar.bar').baz;",
output: 'foo1.foo2.bar.bar.baz;',
options: [{ catchUnsafeObjects: true, useOptionalChaining: true }],
errors: [{ message: ERROR_MESSAGE_GET, type: 'CallExpression' }],
},
{
code: `
import { get } from '@ember/object';
Expand Down Expand Up @@ -372,6 +390,17 @@ ruleTester.run('no-get', rule, {
},
],
},
{
code: "this.get('foo.bar').baz;",
output: 'this.foo.bar.baz;',
options: [{ useOptionalChaining: true }],
errors: [
{
message: ERROR_MESSAGE_GET,
type: 'CallExpression',
},
],
},
{
code: "this.get('very.long.path');",
output: 'this.very?.long?.path;',
Expand Down