Fix bug with the countShips function

This commit is contained in:
Oliver Akins 2022-06-19 12:42:24 -06:00
parent 0f76e83fac
commit 7af5cf0ce8
No known key found for this signature in database
GPG key ID: 3C2014AF9457AF99

View file

@ -10,9 +10,20 @@
* the target ship * the target ship
*/ */
export function countShips(board: any[], shipLocation: number) { 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 { return {
left: board.slice(1, shipLocation - 1).filter(x => x != null).length, left,
right: board.slice(shipLocation + 1).filter(x => x != null).length, right: board.slice(shipLocation + 1).filter(x => x != null).length
}; };
}; };