Skip to content

Commit

Permalink
Fix bug
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed May 3, 2020
1 parent 09a24bb commit b6f1571
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
11 changes: 9 additions & 2 deletions rules/prefer-string-slice.js
Expand Up @@ -71,7 +71,14 @@ const create = context => {
sliceArguments = [firstArgument];
} else if (argumentNodes.length === 2) {
if (firstArgument === '0') {
sliceArguments = [firstArgument, secondArgument];
sliceArguments = [firstArgument];
if (isLiteralNumber(secondArgument) || isLengthProperty(argumentNodes[1])) {
sliceArguments.push(secondArgument)
} else if (getNumericValue(argumentNodes[1]) !== undefined) {
sliceArguments.push(Math.max(0, getNumericValue(argumentNodes[1])))
} else {
sliceArguments.push(`Math.max(0, ${secondArgument})`)
}
} else if (
isLiteralNumber(argumentNodes[0]) &&
isLiteralNumber(argumentNodes[1])
Expand Down Expand Up @@ -124,7 +131,7 @@ const create = context => {
sliceArguments = [`Math.max(0, ${firstArgument})`];
}
} else if (argumentNodes.length === 2) {
const secondNumber = argumentNodes[1] ? getNumericValue(argumentNodes[1]) : undefined;
const secondNumber = getNumericValue(argumentNodes[1]);

if (firstNumber !== undefined && secondNumber !== undefined) {
sliceArguments = firstNumber > secondNumber ?
Expand Down
32 changes: 30 additions & 2 deletions test/prefer-string-slice.js
Expand Up @@ -84,7 +84,7 @@ ruleTester.run('prefer-string-slice', rule, {
`,
output: outdent`
const length = 123;
"foo".slice(0, length)
"foo".slice(0, Math.max(0, length))
`,
errors
},
Expand All @@ -99,6 +99,16 @@ ruleTester.run('prefer-string-slice', rule, {
`,
errors
},
{
code: '"foo".substr(0, -1)',
output: '"foo".slice(0, 0)',
errors
},
{
code: '"foo".substr(0, "foo".length)',
output: '"foo".slice(0, "foo".length)',
errors
},
{
code: outdent`
const length = 123;
Expand Down Expand Up @@ -138,6 +148,18 @@ ruleTester.run('prefer-string-slice', rule, {
code: '"foo".substr(1, 2)',
errors
},
// Extra arguments
{
code: 'foo.substr(1, 2, 3)',
output: 'foo.substr(1, 2, 3)',
errors
},
// #700
{
code: '"Sample".substr(0, "Sample".lastIndexOf("/"))',
output: '"Sample".slice(0, Math.max(0, "Sample".lastIndexOf("/")))',
errors
},

{
code: 'foo.substring()',
Expand Down Expand Up @@ -210,7 +232,13 @@ ruleTester.run('prefer-string-slice', rule, {
{
code: '"foo".substring(1, 3)',
errors
}
},
// Extra arguments
{
code: 'foo.substring(1, 2, 3)',
output: 'foo.substring(1, 2, 3)',
errors
},
]
});

Expand Down

0 comments on commit b6f1571

Please sign in to comment.