Simplify duplicated function call inside if-else statement

Convert an if-else statement with a duplicated function call into a function call with a conditional expression.

Simplify duplicated function call inside if-else statement

If-statements can contain duplicated statements with minimal differences. For example, copy-paste changes can result in such code duplication. The duplication can often be simplified by extracting the difference using the conditional operator and reducing the if-else to the deduplicated statement.

Before (Example)

if (direction === "left") {
  move(original.x, -10);
} else {
  move(original.x, 10);
}

Refactoring Steps

  1. Extract variable twice with the same variable name
  2. Split declaration and initialization of both extracted constants
  3. Move duplicated first statement out of if-else
  4. Move duplicated last statement out of if-else
  5. Convert the if-else statement into a conditional expression
  6. Merge variable declaration and initialization
  7. Inline variable

After (Example)

move(original.x, direction === "left" ? -10 : 10);

Learn More