Skip to content

Commit

Permalink
[Refactor] improve performance for detecting class components
Browse files Browse the repository at this point in the history
  • Loading branch information
golopot authored and ljharb committed Apr 10, 2022
1 parent 8992a2b commit 161317e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -21,7 +21,9 @@ This change log adheres to standards from [Keep a CHANGELOG](https://keepachange
* [Refactor] fix linter errors ([#3261][] @golopot)
* [Docs] [`no-unused-prop-types`]: fix syntax errors ([#3259][] @mrdulin)
* [Refactor] improve performance for detecting function components ([#3265][] @golopot)
* [Refactor] improve performance for detecting class components ([#3267][] @golopot)

[#3267]: https://github.com/yannickcr/eslint-plugin-react/pull/3267
[#3266]: https://github.com/yannickcr/eslint-plugin-react/pull/3266
[#3265]: https://github.com/yannickcr/eslint-plugin-react/pull/3265
[#3261]: https://github.com/yannickcr/eslint-plugin-react/pull/3261
Expand Down
26 changes: 21 additions & 5 deletions lib/util/Components.js
Expand Up @@ -259,20 +259,29 @@ function componentRule(rule, context) {
const utils = {

/**
* Check if the node is a React ES5 component
* Check if an ObjectExpression is a React ES5 component
*
* @param {ASTNode} node The AST node being checked.
* @returns {Boolean} True if the node is a React ES5 component, false if not
*/
isES5Component(node) {
if (!node.parent) {
if (!node.parent || !node.parent.callee) {
return false;
}
return new RegExp(`^(${pragma}\\.)?${createClass}$`).test(sourceCode.getText(node.parent.callee));
const callee = node.parent.callee;
// React.createClass({})
if (callee.type === 'MemberExpression') {
return callee.object.name === pragma && callee.property.name === createClass;
}
// createClass({})
if (callee.type === 'Identifier') {
return callee.name === createClass;
}
return false;
},

/**
* Check if the node is a React ES6 component
* Check if a class is a React ES6 component
*
* @param {ASTNode} node The AST node being checked.
* @returns {Boolean} True if the node is a React ES6 component, false if not
Expand All @@ -285,7 +294,14 @@ function componentRule(rule, context) {
if (!node.superClass) {
return false;
}
return new RegExp(`^(${pragma}\\.)?(Pure)?Component$`).test(sourceCode.getText(node.superClass));
if (node.superClass.type === 'MemberExpression') {
return node.superClass.object.name === pragma
&& /^(Pure)?Component$/.test(node.superClass.property.name);
}
if (node.superClass.type === 'Identifier') {
return /^(Pure)?Component$/.test(node.superClass.name);
}
return false;
},

/**
Expand Down

0 comments on commit 161317e

Please sign in to comment.