prefer-destructuring.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /**
  2. * @fileoverview Prefer destructuring from arrays and objects
  3. * @author Alex LaFroscia
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. type: "suggestion",
  12. docs: {
  13. description: "require destructuring from arrays and/or objects",
  14. category: "ECMAScript 6",
  15. recommended: false,
  16. url: "https://eslint.org/docs/rules/prefer-destructuring"
  17. },
  18. fixable: "code",
  19. schema: [
  20. {
  21. /*
  22. * old support {array: Boolean, object: Boolean}
  23. * new support {VariableDeclarator: {}, AssignmentExpression: {}}
  24. */
  25. oneOf: [
  26. {
  27. type: "object",
  28. properties: {
  29. VariableDeclarator: {
  30. type: "object",
  31. properties: {
  32. array: {
  33. type: "boolean"
  34. },
  35. object: {
  36. type: "boolean"
  37. }
  38. },
  39. additionalProperties: false
  40. },
  41. AssignmentExpression: {
  42. type: "object",
  43. properties: {
  44. array: {
  45. type: "boolean"
  46. },
  47. object: {
  48. type: "boolean"
  49. }
  50. },
  51. additionalProperties: false
  52. }
  53. },
  54. additionalProperties: false
  55. },
  56. {
  57. type: "object",
  58. properties: {
  59. array: {
  60. type: "boolean"
  61. },
  62. object: {
  63. type: "boolean"
  64. }
  65. },
  66. additionalProperties: false
  67. }
  68. ]
  69. },
  70. {
  71. type: "object",
  72. properties: {
  73. enforceForRenamedProperties: {
  74. type: "boolean"
  75. }
  76. },
  77. additionalProperties: false
  78. }
  79. ]
  80. },
  81. create(context) {
  82. const enabledTypes = context.options[0];
  83. const enforceForRenamedProperties = context.options[1] && context.options[1].enforceForRenamedProperties;
  84. let normalizedOptions = {
  85. VariableDeclarator: { array: true, object: true },
  86. AssignmentExpression: { array: true, object: true }
  87. };
  88. if (enabledTypes) {
  89. normalizedOptions = typeof enabledTypes.array !== "undefined" || typeof enabledTypes.object !== "undefined"
  90. ? { VariableDeclarator: enabledTypes, AssignmentExpression: enabledTypes }
  91. : enabledTypes;
  92. }
  93. //--------------------------------------------------------------------------
  94. // Helpers
  95. //--------------------------------------------------------------------------
  96. // eslint-disable-next-line jsdoc/require-description
  97. /**
  98. * @param {string} nodeType "AssignmentExpression" or "VariableDeclarator"
  99. * @param {string} destructuringType "array" or "object"
  100. * @returns {boolean} `true` if the destructuring type should be checked for the given node
  101. */
  102. function shouldCheck(nodeType, destructuringType) {
  103. return normalizedOptions &&
  104. normalizedOptions[nodeType] &&
  105. normalizedOptions[nodeType][destructuringType];
  106. }
  107. /**
  108. * Determines if the given node is accessing an array index
  109. *
  110. * This is used to differentiate array index access from object property
  111. * access.
  112. * @param {ASTNode} node the node to evaluate
  113. * @returns {boolean} whether or not the node is an integer
  114. */
  115. function isArrayIndexAccess(node) {
  116. return Number.isInteger(node.property.value);
  117. }
  118. /**
  119. * Report that the given node should use destructuring
  120. * @param {ASTNode} reportNode the node to report
  121. * @param {string} type the type of destructuring that should have been done
  122. * @param {Function|null} fix the fix function or null to pass to context.report
  123. * @returns {void}
  124. */
  125. function report(reportNode, type, fix) {
  126. context.report({
  127. node: reportNode,
  128. message: "Use {{type}} destructuring.",
  129. data: { type },
  130. fix
  131. });
  132. }
  133. /**
  134. * Determines if a node should be fixed into object destructuring
  135. *
  136. * The fixer only fixes the simplest case of object destructuring,
  137. * like: `let x = a.x`;
  138. *
  139. * Assignment expression is not fixed.
  140. * Array destructuring is not fixed.
  141. * Renamed property is not fixed.
  142. * @param {ASTNode} node the the node to evaluate
  143. * @returns {boolean} whether or not the node should be fixed
  144. */
  145. function shouldFix(node) {
  146. return node.type === "VariableDeclarator" &&
  147. node.id.type === "Identifier" &&
  148. node.init.type === "MemberExpression" &&
  149. node.id.name === node.init.property.name;
  150. }
  151. /**
  152. * Fix a node into object destructuring.
  153. * This function only handles the simplest case of object destructuring,
  154. * see {@link shouldFix}.
  155. * @param {SourceCodeFixer} fixer the fixer object
  156. * @param {ASTNode} node the node to be fixed.
  157. * @returns {Object} a fix for the node
  158. */
  159. function fixIntoObjectDestructuring(fixer, node) {
  160. const rightNode = node.init;
  161. const sourceCode = context.getSourceCode();
  162. return fixer.replaceText(
  163. node,
  164. `{${rightNode.property.name}} = ${sourceCode.getText(rightNode.object)}`
  165. );
  166. }
  167. /**
  168. * Check that the `prefer-destructuring` rules are followed based on the
  169. * given left- and right-hand side of the assignment.
  170. *
  171. * Pulled out into a separate method so that VariableDeclarators and
  172. * AssignmentExpressions can share the same verification logic.
  173. * @param {ASTNode} leftNode the left-hand side of the assignment
  174. * @param {ASTNode} rightNode the right-hand side of the assignment
  175. * @param {ASTNode} reportNode the node to report the error on
  176. * @returns {void}
  177. */
  178. function performCheck(leftNode, rightNode, reportNode) {
  179. if (rightNode.type !== "MemberExpression" || rightNode.object.type === "Super") {
  180. return;
  181. }
  182. if (isArrayIndexAccess(rightNode)) {
  183. if (shouldCheck(reportNode.type, "array")) {
  184. report(reportNode, "array", null);
  185. }
  186. return;
  187. }
  188. const fix = shouldFix(reportNode)
  189. ? fixer => fixIntoObjectDestructuring(fixer, reportNode)
  190. : null;
  191. if (shouldCheck(reportNode.type, "object") && enforceForRenamedProperties) {
  192. report(reportNode, "object", fix);
  193. return;
  194. }
  195. if (shouldCheck(reportNode.type, "object")) {
  196. const property = rightNode.property;
  197. if (
  198. (property.type === "Literal" && leftNode.name === property.value) ||
  199. (property.type === "Identifier" && leftNode.name === property.name && !rightNode.computed)
  200. ) {
  201. report(reportNode, "object", fix);
  202. }
  203. }
  204. }
  205. /**
  206. * Check if a given variable declarator is coming from an property access
  207. * that should be using destructuring instead
  208. * @param {ASTNode} node the variable declarator to check
  209. * @returns {void}
  210. */
  211. function checkVariableDeclarator(node) {
  212. // Skip if variable is declared without assignment
  213. if (!node.init) {
  214. return;
  215. }
  216. // We only care about member expressions past this point
  217. if (node.init.type !== "MemberExpression") {
  218. return;
  219. }
  220. performCheck(node.id, node.init, node);
  221. }
  222. /**
  223. * Run the `prefer-destructuring` check on an AssignmentExpression
  224. * @param {ASTNode} node the AssignmentExpression node
  225. * @returns {void}
  226. */
  227. function checkAssigmentExpression(node) {
  228. if (node.operator === "=") {
  229. performCheck(node.left, node.right, node);
  230. }
  231. }
  232. //--------------------------------------------------------------------------
  233. // Public
  234. //--------------------------------------------------------------------------
  235. return {
  236. VariableDeclarator: checkVariableDeclarator,
  237. AssignmentExpression: checkAssigmentExpression
  238. };
  239. }
  240. };