max-switch-cases.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. "use strict";
  2. /*
  3. * eslint-plugin-sonarjs
  4. * Copyright (C) 2018-2021 SonarSource SA
  5. * mailto:info AT sonarsource DOT com
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 3 of the License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with this program; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  20. */
  21. // https://sonarsource.github.io/rspec/#/rspec/S1479
  22. const docs_url_1 = require("../utils/docs-url");
  23. const DEFAULT_MAX_SWITCH_CASES = 30;
  24. let maxSwitchCases = DEFAULT_MAX_SWITCH_CASES;
  25. const rule = {
  26. meta: {
  27. messages: {
  28. reduceNumberOfNonEmptySwitchCases: 'Reduce the number of non-empty switch cases from {{numSwitchCases}} to at most {{maxSwitchCases}}.',
  29. },
  30. type: 'suggestion',
  31. docs: {
  32. description: '"switch" statements should not have too many "case" clauses',
  33. recommended: 'error',
  34. url: (0, docs_url_1.default)(__filename),
  35. },
  36. schema: [
  37. {
  38. type: 'integer',
  39. minimum: 0,
  40. },
  41. ],
  42. },
  43. create(context) {
  44. if (context.options.length > 0) {
  45. maxSwitchCases = context.options[0];
  46. }
  47. return {
  48. SwitchStatement: (node) => visitSwitchStatement(node, context),
  49. };
  50. },
  51. };
  52. function visitSwitchStatement(switchStatement, context) {
  53. const nonEmptyCases = switchStatement.cases.filter(switchCase => switchCase.consequent.length > 0 && !isDefaultCase(switchCase));
  54. if (nonEmptyCases.length > maxSwitchCases) {
  55. const switchKeyword = context.getSourceCode().getFirstToken(switchStatement);
  56. context.report({
  57. messageId: 'reduceNumberOfNonEmptySwitchCases',
  58. loc: switchKeyword.loc,
  59. data: {
  60. numSwitchCases: nonEmptyCases.length.toString(),
  61. maxSwitchCases: maxSwitchCases.toString(),
  62. },
  63. });
  64. }
  65. }
  66. function isDefaultCase(switchCase) {
  67. return switchCase.test === null;
  68. }
  69. module.exports = rule;
  70. //# sourceMappingURL=max-switch-cases.js.map