var generateMatrix = function(n) {
let ans = new Array(n).fill().map(i => new Array(n).fill(null))
let direction = [[0,1], [1, 0], [0, -1], [-1, 0]]
let x = 0
let y = 0
ans[x][y] = 1
let num = 2
while(num <= n*n) {
x += direction[0][0]
y += direction[0][1]
if (ans[x] === undefined || ans[x][y] === undefined || ans[x][y]) {
x -= direction[0][0]
y -= direction[0][1]
direction.push(direction.shift())
} else if (ans[x][y] === null) {
ans[x][y] = num++
}
}
return ans
};