I am having an issue returning a string that maps the path taken to get to the end of a maze. The function takes a 2-d array maze of string values and an array of 2 elements that represent the starting point of the maze(eg. [0,0]). I am returning the correct path when the function is called once but the string is not reinitialized so I get multiple answers concatenated. Code:
function mazeSolver(maze, index = [0, 0]) {
if (typeof mazeSolver.answer == "undefined") {
mazeSolver.answer = "";
}
const pointer = () => maze[index[0]][index[1]];
if (index[1] < maze[0].length - 1) {
index[1] += 1;
if (pointer() === " " || pointer() === "e") {
mazeSolver.answer += "R";
if (pointer() === "e") return mazeSolver.answer;
return mazeSolver(maze, index);
} else {
if (index[0] < maze.length - 1) {
index[1] -= 1;
index[0] += 1;
if (pointer() === " " || pointer() === "e") {
mazeSolver.answer += "D";
if (pointer() === "e") return mazeSolver.answer;
return mazeSolver(maze, index);
}
}
}
} else if (index[0] < maze.length - 1) {
index[0] += 1;
if (pointer() === " " || pointer() === "e") {
mazeSolver.answer += "D";
if (pointer() === "e") return mazeSolver.answer;
return mazeSolver(maze, index);
}
}
}
const mySmallMaze = [
[" ", "*", " "],
[" ", "*", " "],
[" ", " ", "e"],
];
console.log(mazeSolver(mySmallMaze));
logs: "DDRR" on second call: "DDRRDDRR"