I am just getting started in learning functional programming and want to put that into practice on my personal React development, to develop functional way of thinking.
Here is the question:
In functional programming, immutability is part of its characteristic to avoid mutate data in place. But consider the use of push()
and splice()
on below method, does the usage on both of them acceptable in functional way of programming, given that both const squares = [];
and const boardRows = [];
are not globally defined variable?
renderBoard() {
const squares = [];
const boardRows = [];
const rowBlock = (squares) => (<div className="board-row">{squares[0]}{squares[1]}{squares[2]}</div>);
const div = (boardRows) => (<div>{boardRows[0]}{boardRows[1]}{boardRows[2]}</div>);
let index = 0;
for (var j = 3; j > 0; j--) {
for (var i = 0; i < 3; i++) {
const square = this.renderSquare(index++, [j, i + 1]);
squares.push(square);
}
const boardRow = rowBlock(squares);
boardRows.push(boardRow);
squares.splice(0); //clear array to store squares of next board row
}
return(div(boardRows));
}
No, this probably shouldn't be considered the best way to do it functionally - just as you said, functional programming should avoid mutations, and in this case (like in most cases) the (many) mutations are not necessary. Consider creating the arrays all at once using Array.from
instead, which doesn't require any mutation nor reassignment:
const length = 3;
const boardRows = Array.from({ length }, (_, outer) => {
const j = 3 - outer;
const boardRow = Array.from({ length }, (_, i) => (
this.renderSquare(outer * length + i, [j, i + 1])
))
return rowBlock(boardRow);
});