I am currently developing a Chess game and ran into a problem with code redundancy in my Bishop class. I am trying to create a function that will get all possible moves of a bishop. To do that, I would create a for loop that evaluates all diagonals of the bishop, and break the loop when it hits the end of the board or a piece. The problem with this code is it is redundant, since to evaluate all diagonals a Bishop can go, I must have 4 for loops. A simplified version of the code looks like this
var list = [1,0,0,0,1,0,0,1]; // 1d list
var index = 5; // position of "bishop"
for (let i = index, j = list.length; i < j; i++) {
if (list[i] === 1) { // if true, return instance of 1 and break loop
console.log("first instance of 1 going right, found at " + i);
break;
}
}
for (let i = index; i >= 0; i--) {
if (list[i] === 1) { // if true, return instance of 1 and break loop
console.log("first instance of 1 going left, found at " + i);
break;
}
}
Though this code works, when dealing with a bishop that can move in 4 directions, this is pretty repetitive and can lead to issues in the future. Is there a way that I am able to reduce the 4 for loops (or 2 in the example above) down to 1 without the cost of efficiency? Because the answer requires the correct concept, there isn't much to show my attempts at this problem.