Hi I want to optimize my code so I don't have a lot of if statements. I've been trying to optimize this code witch is inside a Class
if (spot.charAt(1) === "P") this.#getMovesPawn(row, col, validMoves);
if (spot.charAt(1) === "N") this.#getMovesKnight(row, col, validMoves);
if (spot.charAt(1) === "B") this.#getMovesBishoop(row, col, validMoves);
if (spot.charAt(1) === "R") this.#getMovesRook(row, col, validMoves);
if (spot.charAt(1) === "Q") this.#getMovesQueen(row, col, validMoves);
First i tried to try putting all of the functions inside an Object
this.moveFunctions = {"P": this.#getMovesBishoop, "B": this.#getMovesBishoop, "N": this.#getMovesKnight,"Q":this.#getMovesQueen, "R": this.#getMovesRook}
// then executing them
this.moveFunctions["P"](0, 0, []);
but when doing so the this
variable changes from the Class variable where all the info is at to just include the functions
// from this
{
"apple": 1,
"pear": 2
...
}
// to
{"P": this.#getMovesBishoop, "B": this.#getMovesBishoop, "N": this.#getMovesKnight,"Q":this.#getMovesQueen, "R": this.#getMovesRook}
my question is how do i manage to make this.moveFunctions
work or something better? I have searched stackoverflow and google, but nothing i've also tried trying this in python and it worked