diff --git a/common/src/algorithms/movementDirection.ts b/common/src/algorithms/movementDirection.ts index 873b183..29f34ae 100644 --- a/common/src/algorithms/movementDirection.ts +++ b/common/src/algorithms/movementDirection.ts @@ -10,9 +10,20 @@ * the target ship */ export function countShips(board: any[], shipLocation: number) { + if (shipLocation < 0) { + throw new Error("shipLocation must be >= 0"); + }; + + // Ensure that when shipLocation we don't assume all ships are to the left + // of it due to negative indexing in .slice() being supported + let left = 0; + if (shipLocation > 0) { + left = board.slice(0, shipLocation - 1).filter(x => x != null).length; + }; + return { - left: board.slice(1, shipLocation - 1).filter(x => x != null).length, - right: board.slice(shipLocation + 1).filter(x => x != null).length, + left, + right: board.slice(shipLocation + 1).filter(x => x != null).length }; };