no-empty-pattern.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * @fileoverview Rule to disallow an empty pattern
  3. * @author Alberto Rodríguez
  4. */
  5. "use strict";
  6. const astUtils = require("./utils/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. /** @type {import('../types').Rule.RuleModule} */
  11. module.exports = {
  12. meta: {
  13. type: "problem",
  14. defaultOptions: [
  15. {
  16. allowObjectPatternsAsParameters: false,
  17. },
  18. ],
  19. docs: {
  20. description: "Disallow empty destructuring patterns",
  21. recommended: true,
  22. url: "https://eslint.org/docs/latest/rules/no-empty-pattern",
  23. },
  24. schema: [
  25. {
  26. type: "object",
  27. properties: {
  28. allowObjectPatternsAsParameters: {
  29. type: "boolean",
  30. },
  31. },
  32. additionalProperties: false,
  33. },
  34. ],
  35. messages: {
  36. unexpected: "Unexpected empty {{type}} pattern.",
  37. },
  38. },
  39. create(context) {
  40. const [{ allowObjectPatternsAsParameters }] = context.options;
  41. return {
  42. ObjectPattern(node) {
  43. if (node.properties.length > 0) {
  44. return;
  45. }
  46. // Allow {} and {} = {} empty object patterns as parameters when allowObjectPatternsAsParameters is true
  47. if (
  48. allowObjectPatternsAsParameters &&
  49. (astUtils.isFunction(node.parent) ||
  50. (node.parent.type === "AssignmentPattern" &&
  51. astUtils.isFunction(node.parent.parent) &&
  52. node.parent.right.type === "ObjectExpression" &&
  53. node.parent.right.properties.length === 0))
  54. ) {
  55. return;
  56. }
  57. context.report({
  58. node,
  59. messageId: "unexpected",
  60. data: { type: "object" },
  61. });
  62. },
  63. ArrayPattern(node) {
  64. if (node.elements.length === 0) {
  65. context.report({
  66. node,
  67. messageId: "unexpected",
  68. data: { type: "array" },
  69. });
  70. }
  71. },
  72. };
  73. },
  74. };