项目原始demo,不改动
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
 
 
 
 

96 line
2.7 KiB

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