I try to create the function, that takes n×n matrix (array of arrays) returns one array arter traverse in a clockwise snailshell pattern.
For more information: https://www.codewars.com/kata/521c2db8ddc89b9b7a0000c1
But my code is ok only for 3x3 matrix. If it is bigger there is the error "Maximum call stack size exceeded"
Could you pls help me to understand my mistake
My code:
function snail (array) {
let result = []
function resultFilling(arrayForResult) {
if (arrayForResult[0].length === 1) {
result.push(arrayForResult[0][0])
return
}
for (let i = 0; i < arrayForResult.length - 1; i++) {
result.push(arrayForResult[0][i])
}
for (let i = 0; i < arrayForResult.length - 1; i++) {
result.push(arrayForResult[i][arrayForResult.length - 1])
}
for (let i = arrayForResult.length - 1; i > 0; i--) {
result.push(arrayForResult[arrayForResult.length - 1][i])
}
for (let i = arrayForResult.length - 1; i > 0; i--) {
result.push(arrayForResult[i][0])
}
let newArr = array.reduce((accum, item, index) => {
if (index > 0 && index < array.length - 1) {
accum.push(item.splice(1, item.length - 2))
}
return accum
}, [])
if (newArr.length > 0) resultFilling(newArr)
}
resultFilling(array)
return result
}