I'm programming a checkers game in typescript. I'd like to explain some important details to understand how the following code works. In my game coordinates are a string, like "b4". I want to get the neighbors of a piece coordinates, but only the neighbors that make sense depending on the player and if the piece in these coordinates is a king or not. For example, if on "b4" it's player one, I want to get only "a5" and "c5" as possible neighbors.
I wrote the following code to find the neighbors of given coordinates:
type CornerType = {
[key: string]: string | null;
}
const getPieceCornersCoordinates = (coordinates: string, piece: Piece) => {
const {row, col} = convertStringCoordinatesToNumberCoordinates(coordinates);
const columnLeft = ((col - 1) >= 0) ? String.fromCharCode((col - 1) + 97) : false;
const columnRight = col +1 <= 7 ? String.fromCharCode((col + 1) + 97) : false;
const rowUpper = row +1 < 9 ? row +1 : false;
const rowLower = row -1 > 0 ? row -1 : false;
let corners : CornerType = {};
if(piece.isKing){
corners.leftUpper = columnLeft !== false && rowUpper !== false ? columnLeft + rowUpper : null;
corners.rightUpper = columnRight !== false && rowUpper !== false ? columnRight + rowUpper : null;
corners.leftLower = columnLeft !== false && rowLower !== false ? columnLeft + rowLower : null;
corners.rightLower = columnRight !== false && rowLower !== false ? columnRight + rowLower : null;
} else if(piece.player === "Player One"){
corners.leftLower = columnLeft !== false && rowLower !== false ? columnLeft + rowLower : null;
corners.rightLower = columnRight !== false && rowLower !== false ? columnRight + rowLower : null;
} else {
corners.leftUpper = columnLeft !== false && rowUpper !== false ? columnLeft + rowUpper : null;
corners.rightUpper = columnRight !== false && rowUpper !== false ? columnRight + rowUpper : null;
}
deleteNullCorners(corners);
return corners;
}
const deleteNullCorners = (corners: CornerType) => {
for(let key in corners){
if(corners[key] === null){
delete corners[key];
}
}
}
I think this code is not well written, how can I improve it?