Fill out a spiral matrix I got this question during my interview:


  Given an integer N, output an N x N spiral matrix with integers 1 through N. 
  
  Examples: Input:  3
  
  Output: [[1, 2, 3],
           [8, 9, 4],
           [7, 6, 5]]
  
  Input: 1
  
  output: matrix filled out as a spiral  [[1]]


/*PSEUDO:
rowMin = 0
rowMax = n - 1
colMin = 0
colMax = n - 1
counter = 1
matrix = []
create the matrix:
loop from 0 to n - 1
  array 
  loop from 0 to n-1
    push 0 into array
while rowMin &lt;= rowMax and colMin &lt;= colMax
  loop on rowMin from colMin to colMax.  col
    matrix[rowMin][col] becomes counter++
  rowMin++
  loop on colMax and from rowMin to rowMax.  row
    matrix[row][colMax] becomes counter++
  colMax--
  loop on rowMax from colMax to colMin.  col
    matrix[rowMax][col] becomes counter++
  rowMax--
  loop on colMin from rowMax to rowMin.  row
    matrix[row][colMin] becomes counter++
  colMin++
return matrix
*/


const spiralMatrix = (n) =&gt; {
  const matrix = [];
  let rowMin = 0,
    rowMax = n - 1,
    colMin = 0,
    colMax = n - 1,
    counter = 1;

  for (let i = 0; i &lt; n; i++) {
    matrix.push(new Array(n).fill(0));
  }

  while (rowMin &lt;= rowMax &amp;&amp; colMin &lt;= colMax) {
    for (let col = colMin; col &lt;= colMax; col++) {
      matrix[rowMin][col] = counter++;
    }
    rowMin++;
    for (let row = rowMin; row &lt;= rowMax; row++) {
      matrix[row][colMax] = counter++;
    }
    colMax--;
    for (let col = colMax; col &gt;= colMin; col--) {
      matrix[rowMax][col] = counter++;
    }
    rowMax--;
    for (let row = rowMax; row &gt;= rowMin; row--) {
      matrix[row][colMin] = counter++;
    }
    colMin++;
  }

  return matrix;
}

console.log(spiralMatrix(10));
Seems mostly solid to me. I just have two small remarks:




const spiralMatrix = (n) =&gt; {



I'm not a big fan of using the arrow syntax here. The arrow syntax is (mostly) used for inline functions. For a "top level" function I'd prefer a normal, more readable (and hoisted) function declaration:

function spiralMatrix(n) {


The only disadvantage I see is that const prevents accidental overwriting, which I don't see as an serious problem in this case.



And .fill(0) during initialization of the arrays is unnecessary.