1 | /**
|
2 | * @fileoverview A rule to disallow unnecessary `.call()` and `.apply()`.
|
3 | * @author Toru Nagashima
|
4 | */
|
5 |
|
6 | ;
|
7 |
|
8 | const astUtils = require("../ast-utils");
|
9 |
|
10 | //------------------------------------------------------------------------------
|
11 | // Helpers
|
12 | //------------------------------------------------------------------------------
|
13 |
|
14 | /**
|
15 | * Checks whether or not a node is a `.call()`/`.apply()`.
|
16 | * @param {ASTNode} node - A CallExpression node to check.
|
17 | * @returns {boolean} Whether or not the node is a `.call()`/`.apply()`.
|
18 | */
|
19 | function isCallOrNonVariadicApply(node) {
|
20 | return (
|
21 | node.callee.type === "MemberExpression" &&
|
22 | node.callee.property.type === "Identifier" &&
|
23 | node.callee.computed === false &&
|
24 | (
|
25 | (node.callee.property.name === "call" && node.arguments.length >= 1) ||
|
26 | (node.callee.property.name === "apply" && node.arguments.length === 2 && node.arguments[1].type === "ArrayExpression")
|
27 | )
|
28 | );
|
29 | }
|
30 |
|
31 |
|
32 | /**
|
33 | * Checks whether or not `thisArg` is not changed by `.call()`/`.apply()`.
|
34 | * @param {ASTNode|null} expectedThis - The node that is the owner of the applied function.
|
35 | * @param {ASTNode} thisArg - The node that is given to the first argument of the `.call()`/`.apply()`.
|
36 | * @param {SourceCode} sourceCode - The ESLint source code object.
|
37 | * @returns {boolean} Whether or not `thisArg` is not changed by `.call()`/`.apply()`.
|
38 | */
|
39 | function isValidThisArg(expectedThis, thisArg, sourceCode) {
|
40 | if (!expectedThis) {
|
41 | return astUtils.isNullOrUndefined(thisArg);
|
42 | }
|
43 | return astUtils.equalTokens(expectedThis, thisArg, sourceCode);
|
44 | }
|
45 |
|
46 | //------------------------------------------------------------------------------
|
47 | // Rule Definition
|
48 | //------------------------------------------------------------------------------
|
49 |
|
50 | module.exports = {
|
51 | meta: {
|
52 | docs: {
|
53 | description: "disallow unnecessary calls to `.call()` and `.apply()`",
|
54 | category: "Best Practices",
|
55 | recommended: false,
|
56 | url: "https://eslint.org/docs/rules/no-useless-call"
|
57 | },
|
58 |
|
59 | schema: []
|
60 | },
|
61 |
|
62 | create(context) {
|
63 | const sourceCode = context.getSourceCode();
|
64 |
|
65 | return {
|
66 | CallExpression(node) {
|
67 | if (!isCallOrNonVariadicApply(node)) {
|
68 | return;
|
69 | }
|
70 |
|
71 | const applied = node.callee.object;
|
72 | const expectedThis = (applied.type === "MemberExpression") ? applied.object : null;
|
73 | const thisArg = node.arguments[0];
|
74 |
|
75 | if (isValidThisArg(expectedThis, thisArg, sourceCode)) {
|
76 | context.report({ node, message: "unnecessary '.{{name}}()'.", data: { name: node.callee.property.name } });
|
77 | }
|
78 | }
|
79 | };
|
80 | }
|
81 | };
|