Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [prefer-string-starts-ends-with] check for negative start index in slice #1920

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 28 additions & 3 deletions packages/eslint-plugin/src/rules/prefer-string-starts-ends-with.ts
Expand Up @@ -166,6 +166,27 @@ export default createRule({
);
}

/**
* Check if a given node is a negative index expression
*
* E.g. `s.slice(- <expr>)`, `s.substring(s.length - <expr>)`
*
* @param node The node to check.
* @param expectedIndexedNode The node which is expected as the receiver of index expression.
*/
function isNegativeIndexExpression(
node: TSESTree.Node,
expectedIndexedNode: TSESTree.Node,
): boolean {
return (
(node.type === AST_NODE_TYPES.UnaryExpression &&
node.operator === '-') ||
(node.type === AST_NODE_TYPES.BinaryExpression &&
node.operator === '-' &&
isLengthExpression(node.left, expectedIndexedNode))
);
}

/**
* Check if a given node is the expression of the last index.
*
Expand Down Expand Up @@ -538,9 +559,10 @@ export default createRule({
}

const isEndsWith =
callNode.arguments.length === 1 ||
(callNode.arguments.length === 2 &&
isLengthExpression(callNode.arguments[1], node.object));
(callNode.arguments.length === 1 ||
(callNode.arguments.length === 2 &&
isLengthExpression(callNode.arguments[1], node.object))) &&
isNegativeIndexExpression(callNode.arguments[0], node.object);
const isStartsWith =
!isEndsWith &&
callNode.arguments.length === 2 &&
Expand All @@ -564,6 +586,9 @@ export default createRule({
) {
return null;
}
// code being checked is likely mistake:
// unequal length of strings being checked for equality
// or reliant on behavior of substring (negative indices interpreted as 0)
if (isStartsWith) {
if (!isLengthExpression(callNode.arguments[1], eqNode.right)) {
return null;
Expand Down
Expand Up @@ -209,6 +209,12 @@ ruleTester.run('prefer-string-starts-ends-with', rule, {
s.slice(-4, -1) === "bar"
}
`,
// https://github.com/typescript-eslint/typescript-eslint/issues/1690
`
function f(s: string) {
s.slice(1) === "bar"
}
`,
`
function f(s: string) {
pattern.test(s)
Expand Down Expand Up @@ -872,7 +878,7 @@ ruleTester.run('prefer-string-starts-ends-with', rule, {
{
code: `
function f(s: string) {
s.slice(startIndex) === needle // 'startIndex' can be different
s.slice(-length) === needle // 'length' can be different
}
`,
output: null,
Expand Down