default-case.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /**
  2. * @fileoverview require default case in switch statements
  3. * @author Aliaksei Shytkin
  4. */
  5. "use strict";
  6. const DEFAULT_COMMENT_PATTERN = /^no default$/iu;
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. /** @type {import('../types').Rule.RuleModule} */
  11. module.exports = {
  12. meta: {
  13. type: "suggestion",
  14. defaultOptions: [{}],
  15. docs: {
  16. description: "Require `default` cases in `switch` statements",
  17. recommended: false,
  18. url: "https://eslint.org/docs/latest/rules/default-case",
  19. },
  20. schema: [
  21. {
  22. type: "object",
  23. properties: {
  24. commentPattern: {
  25. type: "string",
  26. },
  27. },
  28. additionalProperties: false,
  29. },
  30. ],
  31. messages: {
  32. missingDefaultCase: "Expected a default case.",
  33. },
  34. },
  35. create(context) {
  36. const [options] = context.options;
  37. const commentPattern = options.commentPattern
  38. ? new RegExp(options.commentPattern, "u")
  39. : DEFAULT_COMMENT_PATTERN;
  40. const sourceCode = context.sourceCode;
  41. //--------------------------------------------------------------------------
  42. // Helpers
  43. //--------------------------------------------------------------------------
  44. /**
  45. * Shortcut to get last element of array
  46. * @param {*[]} collection Array
  47. * @returns {any} Last element
  48. */
  49. function last(collection) {
  50. return collection.at(-1);
  51. }
  52. //--------------------------------------------------------------------------
  53. // Public
  54. //--------------------------------------------------------------------------
  55. return {
  56. SwitchStatement(node) {
  57. if (!node.cases.length) {
  58. /*
  59. * skip check of empty switch because there is no easy way
  60. * to extract comments inside it now
  61. */
  62. return;
  63. }
  64. const hasDefault = node.cases.some(v => v.test === null);
  65. if (!hasDefault) {
  66. let comment;
  67. const lastCase = last(node.cases);
  68. const comments = sourceCode.getCommentsAfter(lastCase);
  69. if (comments.length) {
  70. comment = last(comments);
  71. }
  72. if (
  73. !comment ||
  74. !commentPattern.test(comment.value.trim())
  75. ) {
  76. context.report({
  77. node,
  78. messageId: "missingDefaultCase",
  79. });
  80. }
  81. }
  82. },
  83. };
  84. },
  85. };