Skip to content

Commit 17581e2

Browse files
authored
prefer-string-slice: Use getParenthesizedText (#1425)
1 parent 7bdf0dd commit 17581e2

File tree

2 files changed

+7
-20
lines changed

2 files changed

+7
-20
lines changed

rules/prefer-string-slice.js

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

45
const MESSAGE_ID_SUBSTR = 'substr';
56
const MESSAGE_ID_SUBSTRING = 'substring';
@@ -42,20 +43,6 @@ const isLikelyNumeric = node => isLiteralNumber(node) || isLengthProperty(node);
4243
const create = context => {
4344
const sourceCode = context.getSourceCode();
4445

45-
const getNodeText = node => {
46-
const text = sourceCode.getText(node);
47-
const before = sourceCode.getTokenBefore(node);
48-
const after = sourceCode.getTokenAfter(node);
49-
if (
50-
(before && before.type === 'Punctuator' && before.value === '(') &&
51-
(after && after.type === 'Punctuator' && after.value === ')')
52-
) {
53-
return `(${text})`;
54-
}
55-
56-
return text;
57-
};
58-
5946
return templates.visitor({
6047
[substrCallTemplate](node) {
6148
const objectNode = substrCallTemplate.context.getMatch(objectVariable);
@@ -113,7 +100,7 @@ const create = context => {
113100
}
114101

115102
if (sliceArguments) {
116-
const objectText = getNodeText(objectNode);
103+
const objectText = getParenthesizedText(objectNode, sourceCode);
117104
const optionalMemberSuffix = node.callee.optional ? '?' : '';
118105
const optionalCallSuffix = node.optional ? '?.' : '';
119106

@@ -181,7 +168,7 @@ const create = context => {
181168
}
182169

183170
if (sliceArguments) {
184-
const objectText = getNodeText(objectNode);
171+
const objectText = getParenthesizedText(objectNode, sourceCode);
185172
const optionalMemberSuffix = node.callee.optional ? '?' : '';
186173
const optionalCallSuffix = node.optional ? '?.' : '';
187174

test/prefer-string-slice.mjs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -150,11 +150,11 @@ test({
150150
{
151151
code: outdent`
152152
const uri = 'foo';
153-
(uri || '').substr(1)
153+
((uri || '')).substr(1)
154154
`,
155155
output: outdent`
156156
const uri = 'foo';
157-
(uri || '').slice(1)
157+
((uri || '')).slice(1)
158158
`,
159159
errors: errorsSubstr,
160160
},
@@ -292,12 +292,12 @@ test.typescript({
292292
{
293293
code: outdent`
294294
function foo() {
295-
return (bar as string).substring(3);
295+
return ((bar as string)).substring(3);
296296
}
297297
`,
298298
output: outdent`
299299
function foo() {
300-
return (bar as string).slice(3);
300+
return ((bar as string)).slice(3);
301301
}
302302
`,
303303
errors: errorsSubstring,

0 commit comments

Comments
 (0)