Skip to content

Commit

Permalink
Improve no-get with useOptionalChaining - infer when nesting is not o…
Browse files Browse the repository at this point in the history
…ptional when autofixing

  this.get('foo.bar').baz // will error if either foo or bar is nullish "baz of undefined"
  this.foo?.bar?.baz      // (previous behavior) evaluates to `undefined`
  this.foo.bar.baz        // (updated behavior)  errors with either "bar of undefined" or "baz of undefined"

This maintains the behavior more closely when a nested chain contains a nullish value.
  • Loading branch information
raycohen committed Aug 24, 2021
1 parent 9ad7248 commit 4c2366c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
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

0 comments on commit 4c2366c

Please sign in to comment.