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