Fix bug with the countShips function
This commit is contained in:
parent
0f76e83fac
commit
7af5cf0ce8
1 changed files with 13 additions and 2 deletions
|
|
@ -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
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue