Skip to content

Commit b8e72b2

Browse files
committed
fix: array element access at beginning of path string in no-get rule
1 parent ffc71f6 commit b8e72b2

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

lib/rules/no-get.js

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,15 +63,16 @@ function fixGet({
6363
let replacementPath = isInLeftSideOfAssignmentExpression ? path : path.replace(/\./g, '?.');
6464

6565
// Replace any array element access (foo.1 => foo[1] or foo?.[1]).
66-
replacementPath = replacementPath.replace(
67-
/\.(\d+)/g,
68-
isInLeftSideOfAssignmentExpression ? '[$1]' : '.[$1]'
69-
);
66+
replacementPath = replacementPath
67+
.replace(/\.(\d+)/g, isInLeftSideOfAssignmentExpression ? '[$1]' : '.[$1]') // Usages in middle of path.
68+
.replace(/^(\d+)\?\./, isInLeftSideOfAssignmentExpression ? '[$1]' : '[$1]?.'); // Usage at beginning of path.
7069

7170
// Add parenthesis around the object text in case of something like this: get(foo || {}, 'bar')
7271
const objectTextSafe = isValidJSPath(objectText) ? objectText : `(${objectText})`;
7372

74-
return fixer.replaceText(node, `${objectTextSafe}.${replacementPath}`);
73+
const objectPathSeparator = replacementPath.startsWith('[') ? '' : '.';
74+
75+
return fixer.replaceText(node, `${objectTextSafe}${objectPathSeparator}${replacementPath}`);
7576
}
7677

7778
module.exports = {

tests/lib/rules/no-get.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,18 @@ ruleTester.run('no-get', rule, {
436436
},
437437
],
438438
},
439+
{
440+
// Handle array element access at beginning of string, with optional chaining.
441+
code: "this.get('0.foo')",
442+
options: [{ useOptionalChaining: true }],
443+
output: 'this[0]?.foo',
444+
errors: [
445+
{
446+
message: ERROR_MESSAGE_GET,
447+
type: 'CallExpression',
448+
},
449+
],
450+
},
439451
{
440452
// Handle array element access (left side of an assignment).
441453
code: "this.get('foo.0.bar')[123] = 'hello world';",

0 commit comments

Comments
 (0)