2 * @fileoverview A rule to suggest using of the spread operator instead of `.apply()`.
3 * @author Toru Nagashima
8 const astUtils = require("./utils/ast-utils");
10 //------------------------------------------------------------------------------
12 //------------------------------------------------------------------------------
15 * Checks whether or not a node is a `.apply()` for variadic.
16 * @param {ASTNode} node A CallExpression node to check.
17 * @returns {boolean} Whether or not the node is a `.apply()` for variadic.
19 function isVariadicApplyCalling(node) {
21 node.callee.type === "MemberExpression" &&
22 node.callee.property.type === "Identifier" &&
23 node.callee.property.name === "apply" &&
24 node.callee.computed === false &&
25 node.arguments.length === 2 &&
26 node.arguments[1].type !== "ArrayExpression" &&
27 node.arguments[1].type !== "SpreadElement"
33 * Checks whether or not `thisArg` is not changed by `.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 `.apply()`.
36 * @param {RuleContext} context The ESLint rule context object.
37 * @returns {boolean} Whether or not `thisArg` is not changed by `.apply()`.
39 function isValidThisArg(expectedThis, thisArg, context) {
41 return astUtils.isNullOrUndefined(thisArg);
43 return astUtils.equalTokens(expectedThis, thisArg, context);
46 //------------------------------------------------------------------------------
48 //------------------------------------------------------------------------------
55 description: "require spread operators instead of `.apply()`",
56 category: "ECMAScript 6",
58 url: "https://eslint.org/docs/rules/prefer-spread"
66 const sourceCode = context.getSourceCode();
69 CallExpression(node) {
70 if (!isVariadicApplyCalling(node)) {
74 const applied = node.callee.object;
75 const expectedThis = (applied.type === "MemberExpression") ? applied.object : null;
76 const thisArg = node.arguments[0];
78 if (isValidThisArg(expectedThis, thisArg, sourceCode)) {
81 message: "Use the spread operator instead of '.apply()'."