no-useless-switch-case.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. const {isEmptyNode} = require('./ast/index.js');
  3. const getSwitchCaseHeadLocation = require('./utils/get-switch-case-head-location.js');
  4. const MESSAGE_ID_ERROR = 'no-useless-switch-case/error';
  5. const MESSAGE_ID_SUGGESTION = 'no-useless-switch-case/suggestion';
  6. const messages = {
  7. [MESSAGE_ID_ERROR]: 'Useless case in switch statement.',
  8. [MESSAGE_ID_SUGGESTION]: 'Remove this case.',
  9. };
  10. const isEmptySwitchCase = node => node.consequent.every(node => isEmptyNode(node));
  11. /** @param {import('eslint').Rule.RuleContext} context */
  12. const create = context => ({
  13. * 'SwitchStatement[cases.length>1]'(switchStatement) {
  14. const {cases} = switchStatement;
  15. // TypeScript allows multiple `default` cases
  16. const defaultCases = cases.filter(switchCase => switchCase.test === null);
  17. if (defaultCases.length !== 1) {
  18. return;
  19. }
  20. const [defaultCase] = defaultCases;
  21. // We only check cases where the last case is the `default` case
  22. if (defaultCase !== cases[cases.length - 1]) {
  23. return;
  24. }
  25. const uselessCases = [];
  26. for (let index = cases.length - 2; index >= 0; index--) {
  27. const node = cases[index];
  28. if (isEmptySwitchCase(node)) {
  29. uselessCases.unshift(node);
  30. } else {
  31. break;
  32. }
  33. }
  34. for (const node of uselessCases) {
  35. yield {
  36. node,
  37. loc: getSwitchCaseHeadLocation(node, context.getSourceCode()),
  38. messageId: MESSAGE_ID_ERROR,
  39. suggest: [
  40. {
  41. messageId: MESSAGE_ID_SUGGESTION,
  42. /** @param {import('eslint').Rule.RuleFixer} fixer */
  43. fix: fixer => fixer.remove(node),
  44. },
  45. ],
  46. };
  47. }
  48. },
  49. });
  50. /** @type {import('eslint').Rule.RuleModule} */
  51. module.exports = {
  52. create,
  53. meta: {
  54. type: 'suggestion',
  55. docs: {
  56. description: 'Disallow useless case in switch statements.',
  57. },
  58. hasSuggestions: true,
  59. messages,
  60. },
  61. };