Extract array constant from string comparison chain

Convert && !== and || === chains into array.includes.

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)
}

Refactoring Steps

  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)
}

Learn More