Skip to content

Commit

Permalink
fix: issues with no-get autofix with array access in nested path
Browse files Browse the repository at this point in the history
  • Loading branch information
bmish committed Nov 6, 2020
1 parent fcdb389 commit 74634bc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
3 changes: 2 additions & 1 deletion lib/rules/no-get.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ function fixGet({
// Replace any array element access (foo.1 => foo[1] or foo?.[1]).
replacementPath = replacementPath
.replace(/\.(\d+)/g, isInLeftSideOfAssignmentExpression ? '[$1]' : '.[$1]') // Usages in middle of path.
.replace(/^(\d+)\?\./, isInLeftSideOfAssignmentExpression ? '[$1]' : '[$1]?.'); // Usage at beginning of path.
.replace(/^(\d+)\??\./, isInLeftSideOfAssignmentExpression ? '[$1].' : '[$1]?.') // Usage at beginning of path.
.replace(/^(\d+)$/, '[$1]'); // Usage as entire string.

// Add parenthesis around the object text in case of something like this: get(foo || {}, 'bar')
const objectTextSafe = isValidJSPath(objectText) ? objectText : `(${objectText})`;
Expand Down
29 changes: 20 additions & 9 deletions tests/lib/rules/no-get.js
Original file line number Diff line number Diff line change
Expand Up @@ -425,10 +425,10 @@ ruleTester.run('no-get', rule, {
],
},
{
// Handle array element access with optional chaining.
code: "this.get('foo1.0.bar1bar.1')",
// Handle array element access with optional chaining (beginning/middle/end of string).
code: "this.get('0.foo1.1.2.bar1bar.3')",
options: [{ useOptionalChaining: true }],
output: 'this.foo1?.[0]?.bar1bar?.[1]',
output: 'this[0]?.foo1?.[1]?.[2]?.bar1bar?.[3]',
errors: [
{
message: ERROR_MESSAGE_GET,
Expand All @@ -437,10 +437,10 @@ ruleTester.run('no-get', rule, {
],
},
{
// Handle array element access at beginning of string, with optional chaining.
code: "this.get('0.foo')",
// Handle array element access as entire string.
code: "this.get('0')",
options: [{ useOptionalChaining: true }],
output: 'this[0]?.foo',
output: 'this[0]',
errors: [
{
message: ERROR_MESSAGE_GET,
Expand All @@ -449,9 +449,20 @@ ruleTester.run('no-get', rule, {
],
},
{
// Handle array element access (left side of an assignment).
code: "this.get('foo.0.bar')[123] = 'hello world';",
output: "this.foo[0].bar[123] = 'hello world';",
// Handle array element access (left side of an assignment, beginning/middle/end of string).
code: "this.get('0.foo.1.bar.2')[123] = 'hello world';",
output: "this[0].foo[1].bar[2][123] = 'hello world';",
errors: [
{
message: ERROR_MESSAGE_GET,
type: 'CallExpression',
},
],
},
{
// Handle array element access (left side of an assignment, entire string).
code: "this.get('0')[123] = 'hello world';",
output: "this[0][123] = 'hello world';",
errors: [
{
message: ERROR_MESSAGE_GET,
Expand Down

0 comments on commit 74634bc

Please sign in to comment.