I've been grinding some Leetcode for an interview coming up and just completed Square Spiral in Javascript.
Looking for feedback on performance. This ranked faster than 58% of submissions, would there be anyway to increase the speed using a similar implementation to what I have here?
let matrix = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25]
]
var spiralOrder = (matrix) => {
//make copy
var dup=JSON.parse(JSON.stringify(matrix));
//setup variables
let maxX, maxY, baseX, baseY, x, y, vecX, vecY, nums, totalSquares;
//Max indexes for array and sub arrays
maxY=matrix[0].length-1;
maxX=matrix.length-1;
//baseX tells x when it has reached the first sub array.
baseX=0;
//baseY tells y when it has reached the first index of a sub array.
baseY=0;
//our indexes
x=0;
y=0;
//our movement vectors
vecX=0;
vecY=0;
//the count for keeping track of positions iterated
count=0;
//the total amount of squares to be iterated
totalSquares=matrix.length*matrix[0].length;
//return value array
nums=[];
//I don't get how subArrays with only a single element could
//still be considered spiralable, but this if-statement handles
//those edge cases. Thanks Leetcode.
if (matrix[0].length===1) {
for (var i=0;i<matrix.length;i++) {
nums.push(matrix[i][0])
}
return nums
}
//While our iterated count is not equal to the total amount of
//squares to be iterated. When this is true we know we
//have completed the spiral.
while(count!==totalSquares) {
nums.push(dup[x][y]);
count++;
//Our loop iterates around in a spiral. On every turn
//the loop increases the opposite side baseX, baseY,
//maxX or maxY to increase the tightness of the spiral
//as it loops.
//This handles starting the very first iteration, moving right.
if (x===0&&y===0) {
vecX=0;
vecY=1;
//We've reached the top rightmost square, move down.
} else if (x===baseX&&y===maxY) {
vecX=1;
vecY=0;
//We can't increment baseY until we're on
//our second turn downwards.
if (baseX>0) {
baseY+=1;
}
//We've reached bottom rightmost square, move left, increment baseX.
} else if (x===maxX&&y===maxY) {
vecX=0;
vecY=-1;
baseX+=1;
//We've reached bottom leftmost square, move up, decrement maxY.
} else if (x===maxX&&y===baseY) {
vecX=-1;
vecY=0
maxY-=1;
//We've reached top leftmost square, move right, decrement maxX.
} else if (x===baseX&&y===baseY) {
vecX=0;
vecY=1;
maxX-=1;
}
//Increment x or y by the vector.
x+=vecX;
y+=vecY;
}
return nums
}
```

const dup = array2D.map(subArray=>[...subArray]);\$\endgroup\$