I wrote a recursive function that needs to return an object from an array of objects. Each object in the array includes a reference to a neighboring object, as shown below:
{
id: 5,
neighbors: {
north: 1,
east: 6,
south: 9,
west: 4
}
}
This represents the square number 5 on a 4x4 board.
The function requires the array of all board squares, the ID of the current square, and a direction:
function findFarthestEmpty(board, id, direction) {
let nextSquare = board[id].neighbors[direction]
if (nextSquare === null) {
console.log('return last square on board', board[id])
return board[id]
} else {
findFarthestEmpty(board, nextSquare, direction)
}
}
//Test a move.
console.log(typeof(findFarthestEmpty(board, 5, 'north')))
When running the function as shown above, the proper square object is logged on line 4, but the statement "undefined" is returned. Could I be confusing statements and expressions?
If you need the board array:
let board = [ { id: 0,
neighbors: { north: null, east: 1, south: 4, west: null },
meeple: null },
{ id: 1,
neighbors: { north: null, east: 2, south: 5, west: 0 },
meeple: null },
{ id: 2,
neighbors: { north: null, east: 3, south: 6, west: 1 },
meeple: null },
{ id: 3,
neighbors: { north: null, east: null, south: 7, west: 2 },
meeple: null },
{ id: 4,
neighbors: { north: 0, east: 5, south: 8, west: null },
meeple: null },
{ id: 5,
neighbors: { north: 1, east: 6, south: 9, west: 4 },
meeple: null },
{ id: 6,
neighbors: { north: 2, east: 7, south: 10, west: 5 },
meeple: null },
{ id: 7,
neighbors: { north: 3, east: null, south: 11, west: 6 },
meeple: null },
{ id: 8,
neighbors: { north: 4, east: 9, south: 12, west: null },
meeple: null },
{ id: 9,
neighbors: { north: 5, east: 10, south: 13, west: 8 },
meeple: null },
{ id: 10,
neighbors: { north: 6, east: 11, south: 14, west: 9 },
meeple: null },
{ id: 11,
neighbors: { north: 7, east: null, south: 15, west: 10 },
meeple: null },
{ id: 12,
neighbors: { north: 8, east: 13, south: null, west: null },
meeple: null },
{ id: 13,
neighbors: { north: 9, east: 14, south: null, west: 12 },
meeple: null },
{ id: 14,
neighbors: { north: 10, east: 15, south: null, west: 13 },
meeple: null },
{ id: 15,
neighbors: { north: 11, east: null, south: null, west: 14 },
meeple: null } ]