no-empty-pattern.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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('../shared/types').Rule} */
  11. module.exports = {
  12. meta: {
  13. type: "problem",
  14. defaultOptions: [{
  15. allowObjectPatternsAsParameters: false
  16. }],
  17. docs: {
  18. description: "Disallow empty destructuring patterns",
  19. recommended: true,
  20. url: "https://eslint.org/docs/latest/rules/no-empty-pattern"
  21. },
  22. schema: [
  23. {
  24. type: "object",
  25. properties: {
  26. allowObjectPatternsAsParameters: {
  27. type: "boolean"
  28. }
  29. },
  30. additionalProperties: false
  31. }
  32. ],
  33. messages: {
  34. unexpected: "Unexpected empty {{type}} pattern."
  35. }
  36. },
  37. create(context) {
  38. const [{ allowObjectPatternsAsParameters }] = context.options;
  39. return {
  40. ObjectPattern(node) {
  41. if (node.properties.length > 0) {
  42. return;
  43. }
  44. // Allow {} and {} = {} empty object patterns as parameters when allowObjectPatternsAsParameters is true
  45. if (
  46. allowObjectPatternsAsParameters &&
  47. (
  48. astUtils.isFunction(node.parent) ||
  49. (
  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. )
  56. ) {
  57. return;
  58. }
  59. context.report({ node, messageId: "unexpected", data: { type: "object" } });
  60. },
  61. ArrayPattern(node) {
  62. if (node.elements.length === 0) {
  63. context.report({ node, messageId: "unexpected", data: { type: "array" } });
  64. }
  65. }
  66. };
  67. }
  68. };