Sice možná trochu delší na řádky, ale 100% funkcionální bez závislostí na ES2017 (core logika je jen v getSnakePath):
function getSnakePath(playGround, point = { x: 0, y: 0 }, direction = directions[0]) {
const current = playGround[point.y][point.x];
const nextPlayGround = removeXY(playGround, point);
const nextDirection = isInPlayGround(nextPlayGround, point.x + direction.x, point.y + direction.y)
? direction
: turnDirectionRight(direction);
const nextPoint = { x: point.x + nextDirection.x, y: point.y + nextDirection.y };
return [
current,
...isInPlayGround(nextPlayGround, nextPoint.x, nextPoint.y) ? getSnakePath(nextPlayGround, nextPoint, nextDirection) : [],
];
}
const directions = [
{ x: 1, y: 0 },
{ x: 0, y: 1 },
{ x: -1, y: 0 },
{ x: 0, y: -1 },
];
function turnDirectionRight(direction) {
return directions[(directions.indexOf(direction) + 1) % directions.length]
}
function removeXY(array, point) {
return array.reduce((nextArray, subArray, y) => [
...nextArray, y === point.y ? subArray.reduce((nextSubArray, value, x) => [
...nextSubArray, x === point.x ? undefined : value
], []) : subArray
], []);
}
function isInPlayGround(playGround, x, y) {
return y < playGround.length && y >= 0 && x < playGround[y].length && x >= 0 && typeof playGround[y][x] !== 'undefined';
}