When a variable is compared against a string value, the easiest way to start is with a variable === "value"
or variable !== "value"
comparison. Over time, these can grow into longer sequences, e.g. variable === "value1" || variable === "value2" || variable === "value3"
.
The values that the variable is compared to are often a meaningful collection on their own. Refactoring them into an array and using array.includes(variable)
can facilitate reuse and extension, and a meaningful array name can make it easier to understand the code.
Before (Example)
if (extension !== "js"
&& extension !== "ts"
&& extension !== "tsx") {
handleUnsupportedExtension(extension)
}
Refactoring Steps
๐กย ย The refactoring steps are using P42 JavaScript Assistant v1.105
- Convert string comparison chain to array.includes
- Extract the array into a variable
- Move the extracted array variable, e.g., to the top of the file (not shown)
After (Example)
const SUPPORTED_EXTENSIONS = ["js", "ts", "tsx"];
if (!SUPPORTED_EXTENSIONS.includes(extension)) {
handleUnsupportedExtension(extension)
}
Top comments (0)