Skip to content

Commit 03b0946

Browse files
authored
prefer-string-slice: Improve argument type detection (#1664)
1 parent 054436e commit 03b0946

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

rules/prefer-string-slice.js

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use strict';
22
const eslintTemplateVisitor = require('eslint-template-visitor');
33
const {getParenthesizedText} = require('./utils/parentheses.js');
4+
const isNumber = require('./utils/is-number.js');
45

56
const MESSAGE_ID_SUBSTR = 'substr';
67
const MESSAGE_ID_SUBSTRING = 'substring';
@@ -38,8 +39,6 @@ const isLengthProperty = node => (
3839
&& node.property.name === 'length'
3940
);
4041

41-
const isLikelyNumeric = node => isLiteralNumber(node) || isLengthProperty(node);
42-
4342
/** @param {import('eslint').Rule.RuleContext} context */
4443
const create = context => {
4544
const sourceCode = context.getSourceCode();
@@ -89,8 +88,8 @@ const create = context => {
8988
argumentNodes[0].value + argumentNodes[1].value,
9089
];
9190
} else if (
92-
isLikelyNumeric(argumentNodes[0])
93-
&& isLikelyNumeric(argumentNodes[1])
91+
isNumber(argumentNodes[0], context.getScope())
92+
&& isNumber(argumentNodes[1], context.getScope())
9493
) {
9594
sliceArguments = [firstArgument, firstArgument + ' + ' + secondArgument];
9695
}

test/prefer-string-slice.mjs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,11 @@ test({
9292
output: '"foo".slice(1, 3)',
9393
errors: errorsSubstr,
9494
},
95+
{
96+
code: '"foo".substr(bar.length, Math.min(baz, 100))',
97+
output: '"foo".slice(bar.length, bar.length + Math.min(baz, 100))',
98+
errors: errorsSubstr,
99+
},
95100
{
96101
code: '"foo".substr(1, length)',
97102
errors: errorsSubstr,
@@ -110,6 +115,10 @@ test({
110115
const length = 123;
111116
"foo".substr(1, length)
112117
`,
118+
output: outdent`
119+
const length = 123;
120+
"foo".slice(1, 1 + length)
121+
`,
113122
errors: errorsSubstr,
114123
},
115124
{
@@ -145,6 +154,14 @@ test({
145154
const length = 123;
146155
"foo".substr(1, length - 4)
147156
`,
157+
output: outdent`
158+
const length = 123;
159+
"foo".slice(1, 1 + length - 4)
160+
`,
161+
errors: errorsSubstr,
162+
},
163+
{
164+
code: '"foo".substr(1, length)',
148165
errors: errorsSubstr,
149166
},
150167
{

0 commit comments

Comments
 (0)