prefer-spread.js 2.8 KB

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