This content originally appeared on DEV Community and was authored by Lars Grammel
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
if (extension !== "js"
&& extension !== "ts"
&& extension !== "tsx") {
handleUnsupportedExtension(extension)
}
Refactoring Steps
- 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
const SUPPORTED_EXTENSIONS = ["js", "ts", "tsx"];
if (!SUPPORTED_EXTENSIONS.includes(extension)) {
handleUnsupportedExtension(extension)
}
This content originally appeared on DEV Community and was authored by Lars Grammel
Lars Grammel | Sciencx (2022-05-06T14:55:23+00:00) JavaScript Refactoring Combo: Extract array constant from string comparison chain. Retrieved from https://www.scien.cx/2022/05/06/javascript-refactoring-combo-extract-array-constant-from-string-comparison-chain/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.
