Skip to content

Commit

Permalink
prefer-string-slice: Improve argument type detection (#1664)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Dec 28, 2021
1 parent 054436e commit 03b0946
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
7 changes: 3 additions & 4 deletions rules/prefer-string-slice.js
@@ -1,6 +1,7 @@
'use strict';
const eslintTemplateVisitor = require('eslint-template-visitor');
const {getParenthesizedText} = require('./utils/parentheses.js');
const isNumber = require('./utils/is-number.js');

const MESSAGE_ID_SUBSTR = 'substr';
const MESSAGE_ID_SUBSTRING = 'substring';
Expand Down Expand Up @@ -38,8 +39,6 @@ const isLengthProperty = node => (
&& node.property.name === 'length'
);

const isLikelyNumeric = node => isLiteralNumber(node) || isLengthProperty(node);

/** @param {import('eslint').Rule.RuleContext} context */
const create = context => {
const sourceCode = context.getSourceCode();
Expand Down Expand Up @@ -89,8 +88,8 @@ const create = context => {
argumentNodes[0].value + argumentNodes[1].value,
];
} else if (
isLikelyNumeric(argumentNodes[0])
&& isLikelyNumeric(argumentNodes[1])
isNumber(argumentNodes[0], context.getScope())
&& isNumber(argumentNodes[1], context.getScope())
) {
sliceArguments = [firstArgument, firstArgument + ' + ' + secondArgument];
}
Expand Down
17 changes: 17 additions & 0 deletions test/prefer-string-slice.mjs
Expand Up @@ -92,6 +92,11 @@ test({
output: '"foo".slice(1, 3)',
errors: errorsSubstr,
},
{
code: '"foo".substr(bar.length, Math.min(baz, 100))',
output: '"foo".slice(bar.length, bar.length + Math.min(baz, 100))',
errors: errorsSubstr,
},
{
code: '"foo".substr(1, length)',
errors: errorsSubstr,
Expand All @@ -110,6 +115,10 @@ test({
const length = 123;
"foo".substr(1, length)
`,
output: outdent`
const length = 123;
"foo".slice(1, 1 + length)
`,
errors: errorsSubstr,
},
{
Expand Down Expand Up @@ -145,6 +154,14 @@ test({
const length = 123;
"foo".substr(1, length - 4)
`,
output: outdent`
const length = 123;
"foo".slice(1, 1 + length - 4)
`,
errors: errorsSubstr,
},
{
code: '"foo".substr(1, length)',
errors: errorsSubstr,
},
{
Expand Down

0 comments on commit 03b0946

Please sign in to comment.