Skip to content

Commit

Permalink
prefer-string-slice: Keep optional chaining in autofix (#1085)
Browse files Browse the repository at this point in the history
  • Loading branch information
noftaly committed Feb 9, 2021
1 parent ee3a2e5 commit acaf197
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
9 changes: 7 additions & 2 deletions rules/prefer-string-slice.js
Expand Up @@ -104,8 +104,10 @@ const create = context => {

if (sliceArguments) {
const objectText = getNodeText(objectNode);
const optionalMemberSuffix = node.callee.optional ? '?' : '';
const optionalCallSuffix = node.optional ? '?.' : '';

problem.fix = fixer => fixer.replaceText(node, `${objectText}.slice(${sliceArguments.join(', ')})`);
problem.fix = fixer => fixer.replaceText(node, `${objectText}${optionalMemberSuffix}.slice${optionalCallSuffix}(${sliceArguments.join(', ')})`);
}

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

if (sliceArguments) {
const objectText = getNodeText(objectNode);
problem.fix = fixer => fixer.replaceText(node, `${objectText}.slice(${sliceArguments.join(', ')})`);
const optionalMemberSuffix = node.callee.optional ? '?' : '';
const optionalCallSuffix = node.optional ? '?.' : '';

problem.fix = fixer => fixer.replaceText(node, `${objectText}${optionalMemberSuffix}.slice${optionalCallSuffix}(${sliceArguments.join(', ')})`);
}

context.report(problem);
Expand Down
43 changes: 43 additions & 0 deletions test/prefer-string-slice.js
Expand Up @@ -23,6 +23,9 @@ test({
'foo.slice()',
'foo.slice(0)',
'foo.slice(1, 2)',
'foo?.slice(1, 2)',
'foo?.slice?.(1, 2)',
'foo?.bar.baz.slice(1, 2)',
'foo.slice(-3, -2)'
],

Expand All @@ -32,6 +35,46 @@ test({
output: 'foo.slice()',
errors: errorsSubstr
},
{
code: 'foo?.substr()',
output: 'foo?.slice()',
errors: errorsSubstr
},
{
code: 'foo.bar?.substring()',
output: 'foo.bar?.slice()',
errors: errorsSubstring
},
{
code: 'foo?.[0]?.substring()',
output: 'foo?.[0]?.slice()',
errors: errorsSubstring
},
{
code: 'foo.bar.substr?.()',
output: 'foo.bar.slice?.()',
errors: errorsSubstr
},
{
code: 'foo.bar?.substring?.()',
output: 'foo.bar?.slice?.()',
errors: errorsSubstring
},
{
code: 'foo.bar?.baz?.substr()',
output: 'foo.bar?.baz?.slice()',
errors: errorsSubstr
},
{
code: 'foo.bar?.baz.substring()',
output: 'foo.bar?.baz.slice()',
errors: errorsSubstring
},
{
code: 'foo.bar.baz?.substr()',
output: 'foo.bar.baz?.slice()',
errors: errorsSubstr
},
{
code: '"foo".substr()',
output: '"foo".slice()',
Expand Down

0 comments on commit acaf197

Please sign in to comment.