ESLint rule for disallowing the switch statement AND FIX IT
- Complexity:
- Lot of rules and with syntaxes that can conflict with each others.
- Code analyser calculating cyclomatic complexity (Plato/escomplex, eslint complexity rule) will handle each 'case' as an additional complexity (at least by default for escomplex)
- Using other approaches often allow to better handle each cases, including the default one
- Performances:
- JIT (Just-in-Time) JavaScript compilers are 'function based', and
switch
block can include code for a lot of cases that may not need to be handled in most common usages -> handling each case in dedicated functions can help
- JIT (Just-in-Time) JavaScript compilers are 'function based', and
There is plenty of plugins to disallow the switch statement usage:
- The "smells" plugin from Elijah Manor
- The SonarJS "no-small" rule (based on MISRA C/C++ guidelines)
- The "no-switch-statements" rule from Andreas Wiedel
The goal of this one, in addition, is to try to help you to refactor your code without "switch".
npm install --save-dev eslint eslint-plugin-replace-switch
Configure it in package.json
.
{
"name": "my-awesome-project",
"eslintConfig": {
"plugins": [
"replace-switch"
],
"rules": {
"replace-switch/replace-switch": "error"
}
}
}
This plugin exports a recommended
configuration that enforces good practices.
To enable this configuration, use the extends
property in your package.json
.
{
"name": "my-awesome-project",
"eslintConfig": {
"plugins": [
"replace-switch"
],
"extends": "plugin:replace-switch/recommended"
}
}
See ESLint documentation for more information about extending configuration files.
ISC © Alexandre Morgaut