I am trying to make a function so that the code is not duplicated, but I don’t understand how to transfer the arguments to the functions inside, because values ​​are set exactly inside this function. Can someone tell me how to fix duplication, or simplify the code, thanks in advance!

for (pivotRow = 0; pivotRow < rows; pivotRow++) { for (pivotCell = 0; pivotCell < cells; pivotCell++) { for (currentCell = pivotCell + 1; currentCell < cells; currentCell++) { setCurrentDirValue(currentCell, pivotRow); setPivotDirValue(pivotCell, pivotRow); if (checkNearValue(currentDir, pivotDir)) break; } } } for (pivotRow = 0; pivotRow < rows; pivotRow++) { for (pivotCell = 0; pivotCell < cells; pivotCell++) { for (currentCell = pivotCell + 1; currentCell < cells; currentCell++) { setCurrentDirValue(pivotRow, currentCell); setPivotDirValue(pivotRow, pivotCell); if (checkNearValue(currentDir, pivotDir)) break; } } } 

Namely, the arguments of these functions:

 setCurrentDirValue(currentCell, pivotRow); setPivotDirValue(pivotCell, pivotRow); setCurrentDirValue(pivotRow, currentCell); setPivotDirValue(pivotRow, pivotCell); 

    1 answer 1

    As one of the options, simply pass the desired function call option to the parameter.

     function fill(isSwap = false) { for (pivotRow = 0; pivotRow < rows; pivotRow++) { for (pivotCell = 0; pivotCell < cells; pivotCell++) { for (currentCell = pivotCell + 1; currentCell < cells; currentCell++) { if(isSwap) { setCurrentDirValue(currentCell, pivotRow); setPivotDirValue(pivotCell, pivotRow); } else { setCurrentDirValue(pivotRow, currentCell); setPivotDirValue(pivotRow, pivotCell); } if (checkNearValue(currentDir, pivotDir)) break; } } } } 

    And call the desired code

     fill(true); fill(false);