I'm trying to solve a task called Snail: given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise - as you can see in the attached image.
I've already written the function but come across an error. Function works fine for while(result.length<=3) - it returns [1,2,3,4]. But for bigger numbers it shows an error -Uncaught TypeError: Cannot read properties of undefined (reading '2'). I've tried to rewrite the functions in a few different ways but keep seeing this error. I don't have any idea what could be the problem. The function down() is able to to return 4 but somehow it can't reach to 5 and beyond.
Thank you in advance for any help
function snail(array){
let arr=[...array] //copy of a passed array
let result=[] //here function will add next blocks
const y=arr.length; const x=arr[0].length //this is to measure size to stop while
let cY=0,cX=0;//current Y axis and current X axis
/*For the purpose of this function both axes start as 0(top left corner) and when going down is 1 instead of -1 as normally in math*/
while(result.length<=x*y){//this should go throw all of the blocks
result.push(...arr[cY].splice(cX,1,null))//take block and replace it with null
right()//search for a block - by default starts from right function
}
function right(){//goes right(next index of current array)
if(arr[cY][cX 1])
{cX =1}
else{down()}
}
function down(){//goes down(next array of current index)
if(arr[cY 1][cX])
{cY }
else{left()}
}
function left(){//goes left(previous index of current array)
if(arr[cY][cX-1])
{cX--}
else{up()}
}
function up(){//goes up(previous array of current index)
if(arr[cY-1][cX])
{cY--}
else{right()}
}
return result
}
console.log(snail([ [1,2,3],[8,9,4],[7,6,5]]))
CodePudding user response:
You are trying to access an array's element that doesn't exist :
arr[x 1][y]
You concidere this code will return false
(undefined
in fact) if indexes [x 1][y]
doesn't exist
This is true only if arr[x 1]
exist but, when arr[x 1]
doesn't exist you also try to access the y'th element of this array which raises an error.
You should try something like this :
arr[x 1] && arr[x 1][y]
Which will return if first statement is false (undefined
is interpreted as false) so it only check if [y]
when [x 1]
exists.
Using array
method .at()
:
arr.at(x 1).at(y) // (may) raise an error
arr.at(x 1)?.at(y) // return undefined instead
Hope it's clear enought ;)