]> git.proxmox.com Git - pve-eslint.git/blame - eslint/lib/rules/prefer-spread.js
change from CLIEngine to ESLint
[pve-eslint.git] / eslint / lib / rules / prefer-spread.js
CommitLineData
eb39fafa
DC
1/**
2 * @fileoverview A rule to suggest using of the spread operator instead of `.apply()`.
3 * @author Toru Nagashima
4 */
5
6"use strict";
7
8const astUtils = require("./utils/ast-utils");
9
10//------------------------------------------------------------------------------
11// Helpers
12//------------------------------------------------------------------------------
13
14/**
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.
18 */
19function isVariadicApplyCalling(node) {
20 return (
6f036462 21 astUtils.isSpecificMemberAccess(node.callee, null, "apply") &&
eb39fafa
DC
22 node.arguments.length === 2 &&
23 node.arguments[1].type !== "ArrayExpression" &&
24 node.arguments[1].type !== "SpreadElement"
25 );
26}
27
eb39fafa
DC
28/**
29 * Checks whether or not `thisArg` is not changed by `.apply()`.
30 * @param {ASTNode|null} expectedThis The node that is the owner of the applied function.
31 * @param {ASTNode} thisArg The node that is given to the first argument of the `.apply()`.
32 * @param {RuleContext} context The ESLint rule context object.
33 * @returns {boolean} Whether or not `thisArg` is not changed by `.apply()`.
34 */
35function isValidThisArg(expectedThis, thisArg, context) {
36 if (!expectedThis) {
37 return astUtils.isNullOrUndefined(thisArg);
38 }
39 return astUtils.equalTokens(expectedThis, thisArg, context);
40}
41
42//------------------------------------------------------------------------------
43// Rule Definition
44//------------------------------------------------------------------------------
45
46module.exports = {
47 meta: {
48 type: "suggestion",
49
50 docs: {
51 description: "require spread operators instead of `.apply()`",
eb39fafa
DC
52 recommended: false,
53 url: "https://eslint.org/docs/rules/prefer-spread"
54 },
55
56 schema: [],
57 fixable: null,
58
59 messages: {
60 preferSpread: "Use the spread operator instead of '.apply()'."
61 }
62 },
63
64 create(context) {
65 const sourceCode = context.getSourceCode();
66
67 return {
68 CallExpression(node) {
69 if (!isVariadicApplyCalling(node)) {
70 return;
71 }
72
6f036462 73 const applied = astUtils.skipChainExpression(astUtils.skipChainExpression(node.callee).object);
eb39fafa
DC
74 const expectedThis = (applied.type === "MemberExpression") ? applied.object : null;
75 const thisArg = node.arguments[0];
76
77 if (isValidThisArg(expectedThis, thisArg, sourceCode)) {
78 context.report({
79 node,
80 messageId: "preferSpread"
81 });
82 }
83 }
84 };
85 }
86};