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

New: Rule class-methods-use-this option exceptMethods accepts regex #12305

Closed
wants to merge 13 commits into from
4 changes: 3 additions & 1 deletion docs/rules/class-methods-use-this.md
Expand Up @@ -91,11 +91,13 @@ class A {
### Exceptions

```
"class-methods-use-this": [<enabled>, { "exceptMethods": [<...exceptions>] }]
"class-methods-use-this": [<enabled>, { "exceptMethods": [<...exceptions>], "useRegExp": <true or default:false> }]
```

The `exceptMethods` option allows you to pass an array of method names for which you would like to ignore warnings. For example, you might have a spec from an external library that requires you to overwrite a method as a regular function (and not as a static method) and does not use `this` inside the function body. In this case, you can add that method to ignore in the warnings.

The option `useRegExp` option enables the use of regex expressions.

Examples of **incorrect** code for this rule when used without exceptMethods:

```js
Expand Down
15 changes: 14 additions & 1 deletion lib/rules/class-methods-use-this.js
Expand Up @@ -34,6 +34,9 @@ module.exports = {
items: {
type: "string"
}
},
useRegExp: {
type: "boolean"
}
},
additionalProperties: false
Expand All @@ -45,7 +48,13 @@ module.exports = {
},
create(context) {
const config = Object.assign({}, context.options[0]);
const exceptMethods = new Set(config.exceptMethods || []);
let exceptMethods;

if (config.useRegExp) {
exceptMethods = (config.exceptMethods || []).map(e => new RegExp(e, "u"));
} else {
exceptMethods = new Set(config.exceptMethods || []);
}

const stack = [];

Expand Down Expand Up @@ -76,6 +85,10 @@ module.exports = {
* @private
*/
function isIncludedInstanceMethod(node) {
if (config.useRegExp) {
return isInstanceMethod(node) &&
(node.computed || !exceptMethods.find(e => e.test(node.key.name)));
}
return isInstanceMethod(node) &&
(node.computed || !exceptMethods.has(node.key.name));
}
Expand Down