main.js
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
26
27
28
29
30
31
32
33
34
35
36
const squareSpirital = (n) => {
  if ( n && !isNaN(parseInt(n)) && parseInt(n) > 0) {
    let arr = Array(n);
    let x = 0; 
    let y = n;
    let total = n * n--;
    let dx = 1; 
    let dy = 0;
    let i = 1; 
    let j = 0;
    while (y) {
      arr[--y] = [];
    }
    while (i <= total) {
      arr[y][x] = i++;
      x += dx; 
      y += dy;
      if (++j === n) {
        if (dy < 0) {
          x++; 
          y++; 
          n -= 2
        }
        j = dx; 
        dx = -dy; 
        dy = j; 
        j = 0;
      }
    }
    return arr;
  } else {
    return [];
  }
};

console.log(` numbers ${squareSpirital(4)}`);
Native Browser JavaScript