JS Refactoring Combo: Simplify Duplicated Function Call Inside If-Else Statement

Lars Grammel - Apr 29 '22 - - Dev Community

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

Refactoring Steps

Simplify duplicated function call inside if-else statement

๐Ÿ’กย ย The refactoring steps are using P42 JavaScript Assistant v1.99

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