Skip to content

Commit

Permalink
chore: enable some rules from eslint-plugin-unicorn internally (eslin…
Browse files Browse the repository at this point in the history
…t#15878)

* chore: add eslint-plugin-unicorn internally

* Update tests/lib/rules/no-invalid-this.js

Co-authored-by: Brett Zamir <brettz9@yahoo.com>

Co-authored-by: Brett Zamir <brettz9@yahoo.com>
  • Loading branch information
2 people authored and srijan-deepsource committed May 30, 2022
1 parent 96286ec commit bfa3545
Show file tree
Hide file tree
Showing 54 changed files with 111 additions and 99 deletions.
6 changes: 3 additions & 3 deletions Makefile.js
Expand Up @@ -614,7 +614,7 @@ target.gensite = function(prereleaseVersion) {
if (test("-f", fullPath)) {
rm("-rf", fullPath);

if (filePath.indexOf(".md") >= 0 && test("-f", htmlFullPath)) {
if (filePath.includes(".md") && test("-f", htmlFullPath)) {
rm("-rf", htmlFullPath);
}
}
Expand Down Expand Up @@ -673,7 +673,7 @@ target.gensite = function(prereleaseVersion) {
process.stdout.write(`> Updating files (Steps 4-9): ${i}/${length} - ${filePath + " ".repeat(30)}\r`);

// 5. Prepend page title and layout variables at the top of rules
if (path.dirname(filename).indexOf("rules") >= 0) {
if (path.dirname(filename).includes("rules")) {

// Find out if the rule requires a special docs portion (e.g. if it is recommended and/or fixable)
const rule = rules.get(ruleName);
Expand All @@ -696,7 +696,7 @@ target.gensite = function(prereleaseVersion) {
}

// 8. Append first version of ESLint rule was added at.
if (filename.indexOf("rules/") !== -1) {
if (filename.includes("rules/")) {
if (!versions.added[baseName]) {
versions.added[baseName] = getFirstVersionOfFile(sourcePath);
}
Expand Down
6 changes: 2 additions & 4 deletions lib/cli-engine/cli-engine.js
Expand Up @@ -366,9 +366,7 @@ function *iterateRuleDeprecationWarnings(usedConfigArrays) {

// Flatten used configs.
/** @type {ExtractedConfig[]} */
const configs = [].concat(
...usedConfigArrays.map(getUsedExtractedConfigs)
);
const configs = usedConfigArrays.flatMap(getUsedExtractedConfigs);

// Traverse rule configs.
for (const config of configs) {
Expand Down Expand Up @@ -1023,7 +1021,7 @@ class CLIEngine {
let formatterPath;

// if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages)
if (!namespace && normalizedFormatName.indexOf("/") > -1) {
if (!namespace && normalizedFormatName.includes("/")) {
formatterPath = path.resolve(cwd, normalizedFormatName);
} else {
try {
Expand Down
2 changes: 1 addition & 1 deletion lib/cli-engine/lint-result-cache.js
Expand Up @@ -36,7 +36,7 @@ const invalidCacheStrategyErrorMessage = `Cache strategy must be one of: ${valid
*/
function isValidCacheStrategy(cacheStrategy) {
return (
validCacheStrategies.indexOf(cacheStrategy) !== -1
validCacheStrategies.includes(cacheStrategy)
);
}

Expand Down
2 changes: 1 addition & 1 deletion lib/linter/code-path-analysis/code-path-segment.js
Expand Up @@ -100,7 +100,7 @@ class CodePathSegment {
* @returns {boolean} `true` if the segment is coming from the end of a loop.
*/
isLoopedPrevSegment(segment) {
return this.internal.loopedPrevSegments.indexOf(segment) !== -1;
return this.internal.loopedPrevSegments.includes(segment);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/linter/code-path-analysis/code-path-state.js
Expand Up @@ -33,7 +33,7 @@ function addToReturnedOrThrown(dest, others, all, segments) {
const segment = segments[i];

dest.push(segment);
if (others.indexOf(segment) === -1) {
if (!others.includes(segment)) {
all.push(segment);
}
}
Expand Down
2 changes: 1 addition & 1 deletion lib/linter/code-path-analysis/code-path.js
Expand Up @@ -212,7 +212,7 @@ class CodePath {
}

// Reset the flag of skipping if all branches have been skipped.
if (skippedSegment && segment.prevSegments.indexOf(skippedSegment) !== -1) {
if (skippedSegment && segment.prevSegments.includes(skippedSegment)) {
skippedSegment = null;
}
visited[segment.id] = true;
Expand Down
8 changes: 4 additions & 4 deletions lib/rules/accessor-pairs.js
Expand Up @@ -299,12 +299,12 @@ module.exports = {
* @private
*/
function checkPropertyDescriptor(node) {
const namesToCheck = node.properties
const namesToCheck = new Set(node.properties
.filter(p => p.type === "Property" && p.kind === "init" && !p.computed)
.map(({ key }) => key.name);
.map(({ key }) => key.name));

const hasGetter = namesToCheck.includes("get");
const hasSetter = namesToCheck.includes("set");
const hasGetter = namesToCheck.has("get");
const hasSetter = namesToCheck.has("set");

if (checkSetWithoutGet && hasSetter && !hasGetter) {
report(node, "missingGetter");
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/callback-return.js
Expand Up @@ -53,7 +53,7 @@ module.exports = {
if (!node.parent) {
return null;
}
if (types.indexOf(node.parent.type) === -1) {
if (!types.includes(node.parent.type)) {
return findClosestParentOfType(node.parent, types);
}
return node.parent;
Expand Down Expand Up @@ -87,7 +87,7 @@ module.exports = {
* @returns {boolean} Whether or not this function matches our callback name.
*/
function isCallback(node) {
return containsOnlyIdentifiers(node.callee) && callbacks.indexOf(sourceCode.getText(node.callee)) > -1;
return containsOnlyIdentifiers(node.callee) && callbacks.includes(sourceCode.getText(node.callee));
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/capitalized-comments.js
Expand Up @@ -185,7 +185,7 @@ module.exports = {

return Boolean(
previousTokenOrComment &&
["Block", "Line"].indexOf(previousTokenOrComment.type) !== -1
["Block", "Line"].includes(previousTokenOrComment.type)
);
}

Expand Down
2 changes: 1 addition & 1 deletion lib/rules/consistent-this.js
Expand Up @@ -65,7 +65,7 @@ module.exports = {
function checkAssignment(node, name, value) {
const isThis = value.type === "ThisExpression";

if (aliases.indexOf(name) !== -1) {
if (aliases.includes(name)) {
if (!isThis || node.operator && node.operator !== "=") {
reportBadAssignment(node, name);
}
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/dot-notation.js
Expand Up @@ -76,7 +76,7 @@ module.exports = {
function checkComputedProperty(node, value) {
if (
validIdentifier.test(value) &&
(allowKeywords || keywords.indexOf(String(value)) === -1) &&
(allowKeywords || !keywords.includes(String(value))) &&
!(allowPattern && allowPattern.test(value))
) {
const formattedValue = node.property.type === "Literal" ? JSON.stringify(value) : `\`${value}\``;
Expand Down Expand Up @@ -142,7 +142,7 @@ module.exports = {
!allowKeywords &&
!node.computed &&
node.property.type === "Identifier" &&
keywords.indexOf(String(node.property.name)) !== -1
keywords.includes(String(node.property.name))
) {
context.report({
node: node.property,
Expand Down
6 changes: 3 additions & 3 deletions lib/rules/global-require.js
Expand Up @@ -6,7 +6,7 @@

"use strict";

const ACCEPTABLE_PARENTS = [
const ACCEPTABLE_PARENTS = new Set([
"AssignmentExpression",
"VariableDeclarator",
"MemberExpression",
Expand All @@ -16,7 +16,7 @@ const ACCEPTABLE_PARENTS = [
"Program",
"VariableDeclaration",
"ChainExpression"
];
]);

/**
* Finds the eslint-scope reference in the given scope.
Expand Down Expand Up @@ -75,7 +75,7 @@ module.exports = {
const currentScope = context.getScope();

if (node.callee.name === "require" && !isShadowed(currentScope, node.callee)) {
const isGoodRequire = context.getAncestors().every(parent => ACCEPTABLE_PARENTS.indexOf(parent.type) > -1);
const isGoodRequire = context.getAncestors().every(parent => ACCEPTABLE_PARENTS.has(parent.type));

if (!isGoodRequire) {
context.report({ node, messageId: "unexpected" });
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/indent-legacy.js
Expand Up @@ -753,7 +753,7 @@ module.exports = {
if (typeof options.CallExpression.arguments === "number") {
nodeIndent += options.CallExpression.arguments * indentSize;
} else if (options.CallExpression.arguments === "first") {
if (parent.arguments.indexOf(node) !== -1) {
if (parent.arguments.includes(node)) {
nodeIndent = parent.arguments[0].loc.start.column;
}
} else {
Expand Down Expand Up @@ -840,7 +840,7 @@ module.exports = {
"IfStatement", "WhileStatement", "ForStatement", "ForInStatement", "ForOfStatement", "DoWhileStatement", "ClassDeclaration", "TryStatement"
];

if (node.parent && statementsWithProperties.indexOf(node.parent.type) !== -1 && isNodeBodyBlock(node)) {
if (node.parent && statementsWithProperties.includes(node.parent.type) && isNodeBodyBlock(node)) {
indent = getNodeIndent(node.parent).goodChar;
} else if (node.parent && node.parent.type === "CatchClause") {
indent = getNodeIndent(node.parent.parent).goodChar;
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/indent.js
Expand Up @@ -796,7 +796,7 @@ module.exports = {
let statement = node.parent && node.parent.parent;

while (
statement.type === "UnaryExpression" && ["!", "~", "+", "-"].indexOf(statement.operator) > -1 ||
statement.type === "UnaryExpression" && ["!", "~", "+", "-"].includes(statement.operator) ||
statement.type === "AssignmentExpression" ||
statement.type === "LogicalExpression" ||
statement.type === "SequenceExpression" ||
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/jsx-quotes.js
Expand Up @@ -70,7 +70,7 @@ module.exports = {
* @public
*/
function usesExpectedQuotes(node) {
return node.value.indexOf(setting.quote) !== -1 || astUtils.isSurroundedBy(node.raw, setting.quote);
return node.value.includes(setting.quote) || astUtils.isSurroundedBy(node.raw, setting.quote);
}

return {
Expand Down
6 changes: 3 additions & 3 deletions lib/rules/lines-around-comment.js
Expand Up @@ -141,7 +141,7 @@ module.exports = {
comments = sourceCode.getAllComments(),
commentLines = getCommentLineNums(comments),
emptyLines = getEmptyLineNums(lines),
commentAndEmptyLines = commentLines.concat(emptyLines);
commentAndEmptyLines = new Set(commentLines.concat(emptyLines));

/**
* Returns whether or not comments are on lines starting with or ending with code
Expand Down Expand Up @@ -393,7 +393,7 @@ module.exports = {
const nextTokenOrComment = sourceCode.getTokenAfter(token, { includeComments: true });

// check for newline before
if (!exceptionStartAllowed && before && !commentAndEmptyLines.includes(prevLineNum) &&
if (!exceptionStartAllowed && before && !commentAndEmptyLines.has(prevLineNum) &&
!(astUtils.isCommentToken(previousTokenOrComment) && astUtils.isTokenOnSameLine(previousTokenOrComment, token))) {
const lineStart = token.range[0] - token.loc.start.column;
const range = [lineStart, lineStart];
Expand All @@ -408,7 +408,7 @@ module.exports = {
}

// check for newline after
if (!exceptionEndAllowed && after && !commentAndEmptyLines.includes(nextLineNum) &&
if (!exceptionEndAllowed && after && !commentAndEmptyLines.has(nextLineNum) &&
!(astUtils.isCommentToken(nextTokenOrComment) && astUtils.isTokenOnSameLine(token, nextTokenOrComment))) {
context.report({
node: token,
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/max-lines.js
Expand Up @@ -159,10 +159,10 @@ module.exports = {
if (skipComments) {
const comments = sourceCode.getAllComments();

const commentLines = comments.flatMap(getLinesWithoutCode);
const commentLines = new Set(comments.flatMap(getLinesWithoutCode));

lines = lines.filter(
l => !commentLines.includes(l.lineNumber)
l => !commentLines.has(l.lineNumber)
);
}

Expand Down
2 changes: 1 addition & 1 deletion lib/rules/newline-before-return.js
Expand Up @@ -47,7 +47,7 @@ module.exports = {
function isPrecededByTokens(node, testTokens) {
const tokenBefore = sourceCode.getTokenBefore(node);

return testTokens.some(token => tokenBefore.value === token);
return testTokens.includes(tokenBefore.value);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/no-bitwise.js
Expand Up @@ -76,7 +76,7 @@ module.exports = {
* @returns {boolean} Whether or not the node has a bitwise operator.
*/
function hasBitwiseOperator(node) {
return BITWISE_OPERATORS.indexOf(node.operator) !== -1;
return BITWISE_OPERATORS.includes(node.operator);
}

/**
Expand All @@ -85,7 +85,7 @@ module.exports = {
* @returns {boolean} Whether or not the node has a bitwise operator.
*/
function allowedOperator(node) {
return allowed.indexOf(node.operator) !== -1;
return allowed.includes(node.operator);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/no-console.js
Expand Up @@ -72,7 +72,7 @@ module.exports = {
function isAllowed(node) {
const propertyName = astUtils.getStaticPropertyName(node);

return propertyName && allowed.indexOf(propertyName) !== -1;
return propertyName && allowed.includes(propertyName);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/no-empty-function.js
Expand Up @@ -144,7 +144,7 @@ module.exports = {
filter: astUtils.isCommentToken
});

if (allowed.indexOf(kind) === -1 &&
if (!allowed.includes(kind) &&
node.body.type === "BlockStatement" &&
node.body.body.length === 0 &&
innerComments.length === 0
Expand Down
6 changes: 3 additions & 3 deletions lib/rules/no-extra-boolean-cast.js
Expand Up @@ -51,13 +51,13 @@ module.exports = {
const sourceCode = context.getSourceCode();

// Node types which have a test which will coerce values to booleans.
const BOOLEAN_NODE_TYPES = [
const BOOLEAN_NODE_TYPES = new Set([
"IfStatement",
"DoWhileStatement",
"WhileStatement",
"ConditionalExpression",
"ForStatement"
];
]);

/**
* Check if a node is a Boolean function or constructor.
Expand Down Expand Up @@ -95,7 +95,7 @@ module.exports = {
(isBooleanFunctionOrConstructorCall(node.parent) &&
node === node.parent.arguments[0]) ||

(BOOLEAN_NODE_TYPES.indexOf(node.parent.type) !== -1 &&
(BOOLEAN_NODE_TYPES.has(node.parent.type) &&
node === node.parent.test) ||

// !<bool>
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/no-extra-semi.js
Expand Up @@ -98,7 +98,7 @@ module.exports = {
"WithStatement"
];

if (allowedParentTypes.indexOf(parent.type) === -1) {
if (!allowedParentTypes.includes(parent.type)) {
report(node);
}
},
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/no-global-assign.js
Expand Up @@ -78,7 +78,7 @@ module.exports = {
* @returns {void}
*/
function checkVariable(variable) {
if (variable.writeable === false && exceptions.indexOf(variable.name) === -1) {
if (variable.writeable === false && !exceptions.includes(variable.name)) {
variable.references.forEach(checkReference);
}
}
Expand Down
12 changes: 6 additions & 6 deletions lib/rules/no-implicit-coercion.js
Expand Up @@ -257,15 +257,15 @@ module.exports = {
let operatorAllowed;

// !!foo
operatorAllowed = options.allow.indexOf("!!") >= 0;
operatorAllowed = options.allow.includes("!!");
if (!operatorAllowed && options.boolean && isDoubleLogicalNegating(node)) {
const recommendation = `Boolean(${sourceCode.getText(node.argument.argument)})`;

report(node, recommendation, true);
}

// ~foo.indexOf(bar)
operatorAllowed = options.allow.indexOf("~") >= 0;
operatorAllowed = options.allow.includes("~");
if (!operatorAllowed && options.boolean && isBinaryNegatingOfIndexOf(node)) {

// `foo?.indexOf(bar) !== -1` will be true (== found) if the `foo` is nullish. So use `>= 0` in that case.
Expand All @@ -276,7 +276,7 @@ module.exports = {
}

// +foo
operatorAllowed = options.allow.indexOf("+") >= 0;
operatorAllowed = options.allow.includes("+");
if (!operatorAllowed && options.number && node.operator === "+" && !isNumeric(node.argument)) {
const recommendation = `Number(${sourceCode.getText(node.argument)})`;

Expand All @@ -289,7 +289,7 @@ module.exports = {
let operatorAllowed;

// 1 * foo
operatorAllowed = options.allow.indexOf("*") >= 0;
operatorAllowed = options.allow.includes("*");
const nonNumericOperand = !operatorAllowed && options.number && isMultiplyByOne(node) && getNonNumericOperand(node);

if (nonNumericOperand) {
Expand All @@ -299,7 +299,7 @@ module.exports = {
}

// "" + foo
operatorAllowed = options.allow.indexOf("+") >= 0;
operatorAllowed = options.allow.includes("+");
if (!operatorAllowed && options.string && isConcatWithEmptyString(node)) {
const recommendation = `String(${sourceCode.getText(getNonEmptyOperand(node))})`;

Expand All @@ -310,7 +310,7 @@ module.exports = {
AssignmentExpression(node) {

// foo += ""
const operatorAllowed = options.allow.indexOf("+") >= 0;
const operatorAllowed = options.allow.includes("+");

if (!operatorAllowed && options.string && isAppendEmptyString(node)) {
const code = sourceCode.getText(getNonEmptyOperand(node));
Expand Down

0 comments on commit bfa3545

Please sign in to comment.