default-case-last.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * @fileoverview Rule to enforce default clauses in switch statements to be last
  3. * @author Milos Djermanovic
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. /** @type {import('../shared/types').Rule} */
  10. module.exports = {
  11. meta: {
  12. type: "suggestion",
  13. docs: {
  14. description: "Enforce default clauses in switch statements to be last",
  15. recommended: false,
  16. url: "https://eslint.org/docs/rules/default-case-last"
  17. },
  18. schema: [],
  19. messages: {
  20. notLast: "Default clause should be the last clause."
  21. }
  22. },
  23. create(context) {
  24. return {
  25. SwitchStatement(node) {
  26. const cases = node.cases,
  27. indexOfDefault = cases.findIndex(c => c.test === null);
  28. if (indexOfDefault !== -1 && indexOfDefault !== cases.length - 1) {
  29. const defaultClause = cases[indexOfDefault];
  30. context.report({ node: defaultClause, messageId: "notLast" });
  31. }
  32. }
  33. };
  34. }
  35. };