DEV Community

Cover image for JS Refactoring Combo: Extract Array Constant From String Comparison Chain
Lars Grammel for P42

Posted on • Updated on • Originally published at p42.ai

JS Refactoring Combo: Extract Array Constant From String Comparison Chain

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)
}
Enter fullscreen mode Exit fullscreen mode

Refactoring Steps

Extract array constant from string comparison chain

πŸ’‘Β Β The refactoring steps are using P42 JavaScript Assistant v1.105

  1. Convert string comparison chain to array.includes
  2. Extract the array into a variable
  3. 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)
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)