Skip to content

Commit acaf197

Browse files
authored
prefer-string-slice: Keep optional chaining in autofix (#1085)
1 parent ee3a2e5 commit acaf197

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

rules/prefer-string-slice.js

+7-2
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,10 @@ const create = context => {
104104

105105
if (sliceArguments) {
106106
const objectText = getNodeText(objectNode);
107+
const optionalMemberSuffix = node.callee.optional ? '?' : '';
108+
const optionalCallSuffix = node.optional ? '?.' : '';
107109

108-
problem.fix = fixer => fixer.replaceText(node, `${objectText}.slice(${sliceArguments.join(', ')})`);
110+
problem.fix = fixer => fixer.replaceText(node, `${objectText}${optionalMemberSuffix}.slice${optionalCallSuffix}(${sliceArguments.join(', ')})`);
109111
}
110112

111113
context.report(problem);
@@ -158,7 +160,10 @@ const create = context => {
158160

159161
if (sliceArguments) {
160162
const objectText = getNodeText(objectNode);
161-
problem.fix = fixer => fixer.replaceText(node, `${objectText}.slice(${sliceArguments.join(', ')})`);
163+
const optionalMemberSuffix = node.callee.optional ? '?' : '';
164+
const optionalCallSuffix = node.optional ? '?.' : '';
165+
166+
problem.fix = fixer => fixer.replaceText(node, `${objectText}${optionalMemberSuffix}.slice${optionalCallSuffix}(${sliceArguments.join(', ')})`);
162167
}
163168

164169
context.report(problem);

test/prefer-string-slice.js

+43
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ test({
2323
'foo.slice()',
2424
'foo.slice(0)',
2525
'foo.slice(1, 2)',
26+
'foo?.slice(1, 2)',
27+
'foo?.slice?.(1, 2)',
28+
'foo?.bar.baz.slice(1, 2)',
2629
'foo.slice(-3, -2)'
2730
],
2831

@@ -32,6 +35,46 @@ test({
3235
output: 'foo.slice()',
3336
errors: errorsSubstr
3437
},
38+
{
39+
code: 'foo?.substr()',
40+
output: 'foo?.slice()',
41+
errors: errorsSubstr
42+
},
43+
{
44+
code: 'foo.bar?.substring()',
45+
output: 'foo.bar?.slice()',
46+
errors: errorsSubstring
47+
},
48+
{
49+
code: 'foo?.[0]?.substring()',
50+
output: 'foo?.[0]?.slice()',
51+
errors: errorsSubstring
52+
},
53+
{
54+
code: 'foo.bar.substr?.()',
55+
output: 'foo.bar.slice?.()',
56+
errors: errorsSubstr
57+
},
58+
{
59+
code: 'foo.bar?.substring?.()',
60+
output: 'foo.bar?.slice?.()',
61+
errors: errorsSubstring
62+
},
63+
{
64+
code: 'foo.bar?.baz?.substr()',
65+
output: 'foo.bar?.baz?.slice()',
66+
errors: errorsSubstr
67+
},
68+
{
69+
code: 'foo.bar?.baz.substring()',
70+
output: 'foo.bar?.baz.slice()',
71+
errors: errorsSubstring
72+
},
73+
{
74+
code: 'foo.bar.baz?.substr()',
75+
output: 'foo.bar.baz?.slice()',
76+
errors: errorsSubstr
77+
},
3578
{
3679
code: '"foo".substr()',
3780
output: '"foo".slice()',

0 commit comments

Comments
 (0)