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