I am a beginner in coding and I can not figure out how to deal with a 'code/function structuring issue'. So when you write a function and the function is starting to have more subordinate functions... I mean it starts to be a multilevel function, I don't know how I should structure my code that it remains to be clean and readable.
Here is an example code, which is part of a tic-tac-toe game
function gameOver(gameWonObj) {
if (gameWonObj === 'tie') {
higlightAllFields();
disableClickOnFields();
declaireWinner('tie');
} else {
highlightWinningHits();
disableClickOnFields();
declaireWinner(gameWonObj.player);
}
function higlightAllFields() {
allSquaresIds = ORIG_BOARD;
for ([idOfSquare, currValue] of allSquaresIds.entries()) {
currSquare = document.getElementById(idOfSquare);
currSquare.style.backgroundColor = TIE_COLOR;
}
}
function highlightWinningHits() {
winningSquaresIds = WIN_COMBOS[gameWonObj.index];
highlightColor = (gameWonObj.player === HU_PLAYERS_SIGN) ? WINNER_COLOR : LOOSER_COLOR;
winningSquaresIds.forEach(currentId => {
currentWinningSquare = document.getElementById(currentId);
currentWinningSquare.style.backgroundColor = highlightColor;
});
}
function disableClickOnFields() {
CELLS.forEach(cell => {
cell.removeEventListener('click', turnClick, false)
})
}
function declaireWinner(player) {
if (player === 'tie') {
declaireWinnerOnModal('ITS A TIE GAME', 'blue')
} else if (player === HU_PLAYERS_SIGN) {
declaireWinnerOnModal('YOU WON', 'lightgreen')
} else if (player === AI_PLAYERS_SIGN) {
declaireWinnerOnModal('AI WON', 'red')
}
function declaireWinnerOnModal(message, textColor) {
END_GAME_MODAL.style.display = 'block';
END_GAME_MODAL.style.color = textColor;
END_GAME_MODAL.innerHTML = `<p>${message}</p>`;
}
}
}
In this example, I have a main function: gameOver
, and it goes a level deeper in functions: declaireWinner
, disableClickOnFields
, higlightAllFields
, declaireWinnerOnModal
.
So when you have lets say an additional layer of functions in one of the sub-functions in your main function the code really gets to be unreadable, too long and overwhelming.
When I started to write into my main app.js
file, I was thinking about what should be the main constroller. Then I wouldn't go one level deeper and I would import all the necessary functions needed by my first level functions. Here, I would import all of the functions which are needed to the function gameOver
.
But then I should pass into gameOver
all of the global and every other variable which I have declared lexically above gameOver
and then the function definitions and call would be really long and ugly: gameOver(global1,global2,global3,global4,...)
And the functions I have imported in, wouldn't have access to the variable object of the parent function and so I should pass again as parameters all variables which the second level of function - and there subordinated functions - need.