no-duplicate-case.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * @fileoverview Rule to disallow a duplicate case label.
  3. * @author Dieter Oberkofler
  4. * @author Burak Yigit Kaya
  5. */
  6. "use strict";
  7. //------------------------------------------------------------------------------
  8. // Requirements
  9. //------------------------------------------------------------------------------
  10. const astUtils = require("./utils/ast-utils");
  11. //------------------------------------------------------------------------------
  12. // Rule Definition
  13. //------------------------------------------------------------------------------
  14. /** @type {import('../shared/types').Rule} */
  15. module.exports = {
  16. meta: {
  17. type: "problem",
  18. docs: {
  19. description: "Disallow duplicate case labels",
  20. recommended: true,
  21. url: "https://eslint.org/docs/rules/no-duplicate-case"
  22. },
  23. schema: [],
  24. messages: {
  25. unexpected: "Duplicate case label."
  26. }
  27. },
  28. create(context) {
  29. const sourceCode = context.getSourceCode();
  30. /**
  31. * Determines whether the two given nodes are considered to be equal.
  32. * @param {ASTNode} a First node.
  33. * @param {ASTNode} b Second node.
  34. * @returns {boolean} `true` if the nodes are considered to be equal.
  35. */
  36. function equal(a, b) {
  37. if (a.type !== b.type) {
  38. return false;
  39. }
  40. return astUtils.equalTokens(a, b, sourceCode);
  41. }
  42. return {
  43. SwitchStatement(node) {
  44. const previousTests = [];
  45. for (const switchCase of node.cases) {
  46. if (switchCase.test) {
  47. const test = switchCase.test;
  48. if (previousTests.some(previousTest => equal(previousTest, test))) {
  49. context.report({ node: switchCase, messageId: "unexpected" });
  50. } else {
  51. previousTests.push(test);
  52. }
  53. }
  54. }
  55. }
  56. };
  57. }
  58. };