forked from sindresorhus/eslint-plugin-unicorn
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prefer-includes.js
85 lines (72 loc) · 2.39 KB
/
prefer-includes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
'use strict';
const getDocumentationUrl = require('./utils/get-documentation-url');
const isMethodNamed = require('./utils/is-method-named');
const isLiteralValue = require('./utils/is-literal-value');
const MESSAGE_ID = 'prefer-includes';
const messages = {
[MESSAGE_ID]: 'Use `.includes()`, rather than `.indexOf()`, when checking for existence.'
};
// Ignore {_,lodash,underscore}.indexOf
const ignoredVariables = new Set(['_', 'lodash', 'underscore']);
const isIgnoredTarget = node => node.type === 'Identifier' && ignoredVariables.has(node.name);
const isNegativeOne = node => node.type === 'UnaryExpression' && node.operator === '-' && node.argument && node.argument.type === 'Literal' && node.argument.value === 1;
const isLiteralZero = node => isLiteralValue(node, 0);
const isNegativeResult = node => ['===', '==', '<'].includes(node.operator);
const report = (context, node, target, argumentsNodes) => {
const sourceCode = context.getSourceCode();
const memberExpressionNode = target.parent;
const dotToken = sourceCode.getTokenBefore(memberExpressionNode.property);
const targetSource = sourceCode.getText().slice(memberExpressionNode.range[0], dotToken.range[0]);
// Strip default `fromIndex`
if (isLiteralZero(argumentsNodes[1])) {
argumentsNodes = argumentsNodes.slice(0, 1);
}
const argumentsSource = argumentsNodes.map(argument => sourceCode.getText(argument));
context.report({
node: memberExpressionNode.property,
messageId: MESSAGE_ID,
fix: fixer => {
const replacement = `${isNegativeResult(node) ? '!' : ''}${targetSource}.includes(${argumentsSource.join(', ')})`;
return fixer.replaceText(node, replacement);
}
});
};
const create = context => ({
BinaryExpression: node => {
const {left, right, operator} = node;
if (!isMethodNamed(left, 'indexOf')) {
return;
}
const target = left.callee.object;
if (isIgnoredTarget(target)) {
return;
}
const {arguments: argumentsNodes} = left;
// Ignore something.indexOf(foo, 0, another)
if (argumentsNodes.length > 2) {
return;
}
if (
(['!==', '!=', '>', '===', '=='].includes(operator) && isNegativeOne(right)) ||
(['>=', '<'].includes(operator) && isLiteralZero(right))
) {
report(
context,
node,
target,
argumentsNodes
);
}
}
});
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
url: getDocumentationUrl(__filename)
},
fixable: 'code',
messages
}
};