Skip to content

Commit

Permalink
fix(eslint-plugin): [prefer-string-starts-ends-with] check for negati…
Browse files Browse the repository at this point in the history
…ve start index in slice (#1920)
  • Loading branch information
sinyovercosy committed Apr 27, 2020
1 parent a85c3e1 commit ed2bd60
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
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

0 comments on commit ed2bd60

Please sign in to comment.