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
๐กย ย The refactoring steps are using P42 JavaScript Assistant v1.99
- Extract variable twice with the same variable name
- Split declaration and initialization of both extracted constants
- Move duplicated first statement out of if-else
- Move duplicated last statement out of if-else
- Convert the if-else statement into a conditional expression
- Merge variable declaration and initialization
- Inline variable
After (Example)
move(original.x, direction === "left" ? -10 : 10);