]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/no-useless-call.js
89350665fe37723d8e745beae1f65714984c5d78
[pve-eslint.git] / eslint / lib / rules / no-useless-call.js
1 /**
2 * @fileoverview A rule to disallow unnecessary `.call()` and `.apply()`.
3 * @author Toru Nagashima
4 */
5
6 "use strict";
7
8 const astUtils = require("./utils/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 const callee = astUtils.skipChainExpression(node.callee);
21
22 return (
23 callee.type === "MemberExpression" &&
24 callee.property.type === "Identifier" &&
25 callee.computed === false &&
26 (
27 (callee.property.name === "call" && node.arguments.length >= 1) ||
28 (callee.property.name === "apply" && node.arguments.length === 2 && node.arguments[1].type === "ArrayExpression")
29 )
30 );
31 }
32
33
34 /**
35 * Checks whether or not `thisArg` is not changed by `.call()`/`.apply()`.
36 * @param {ASTNode|null} expectedThis The node that is the owner of the applied function.
37 * @param {ASTNode} thisArg The node that is given to the first argument of the `.call()`/`.apply()`.
38 * @param {SourceCode} sourceCode The ESLint source code object.
39 * @returns {boolean} Whether or not `thisArg` is not changed by `.call()`/`.apply()`.
40 */
41 function isValidThisArg(expectedThis, thisArg, sourceCode) {
42 if (!expectedThis) {
43 return astUtils.isNullOrUndefined(thisArg);
44 }
45 return astUtils.equalTokens(expectedThis, thisArg, sourceCode);
46 }
47
48 //------------------------------------------------------------------------------
49 // Rule Definition
50 //------------------------------------------------------------------------------
51
52 module.exports = {
53 meta: {
54 type: "suggestion",
55
56 docs: {
57 description: "disallow unnecessary calls to `.call()` and `.apply()`",
58 recommended: false,
59 url: "https://eslint.org/docs/rules/no-useless-call"
60 },
61
62 schema: [],
63
64 messages: {
65 unnecessaryCall: "Unnecessary '.{{name}}()'."
66 }
67 },
68
69 create(context) {
70 const sourceCode = context.getSourceCode();
71
72 return {
73 CallExpression(node) {
74 if (!isCallOrNonVariadicApply(node)) {
75 return;
76 }
77
78 const callee = astUtils.skipChainExpression(node.callee);
79 const applied = astUtils.skipChainExpression(callee.object);
80 const expectedThis = (applied.type === "MemberExpression") ? applied.object : null;
81 const thisArg = node.arguments[0];
82
83 if (isValidThisArg(expectedThis, thisArg, sourceCode)) {
84 context.report({ node, messageId: "unnecessaryCall", data: { name: callee.property.name } });
85 }
86 }
87 };
88 }
89 };