From 7af5cf0ce83260470424b52f493b84cef028c4b5 Mon Sep 17 00:00:00 2001 From: Oliver Akins Date: Sun, 19 Jun 2022 12:42:24 -0600 Subject: [PATCH] Fix bug with the countShips function --- common/src/algorithms/movementDirection.ts | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) 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 }; };