Having a small issue with my recursion. I've created a function that checks for matching directions of clicked boxes.
const checkMatchingDirections = (board, r, c) => {
const top = board[r - 1] !== undefined && { row: r - 1, column: c };
const bottom = board[r + 1] !== undefined && { row: r + 1, column: c };
const left = board[r][c - 1] !== undefined && { row: r, column: c - 1 };
const right = board[r][c + 1] !== undefined && { row: r, column: c + 1 };
// filtering for edge blocks and finding color matches
const directionsWithMatches = [top, bottom, left, right]
.filter(dir => dir instanceof Object)
.filter(({ row, column }) => board[row][column].color === board[r][c].color);
return directionsWithMatches;
};
The function returns an array of matching colors for the clicked box.
My issue lies in how to recursively call the function checkMatchingDirections on the results of the previous array returned by the function.
Currently, I'm using the following approach
const matches = checkMatchingDirections(blocks, y, x);
matches.map(({ row, column }) => {
const restMatches = checkMatchingDirections(blocks, row, column);
allMatchingBlocks = [...matches, ...allMatchingBlocks, ...restMatches];
});
The problem is that it's hardcoded to recall the function twice by mapping the results of checkMatchingDirection in the initial call.
How can I create a function that will recursively call checkMatchingDirection on the array of results from checkMatchingDirection?
For example,
If I click on a green box and there are four boxes on the left and one on the top that should all be selected.