Spiral-order-matrix-ii: JavaScript heap out of memory


#1

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

Submission keeps crashing, despite the fact the my code works perfectly ok, and correct in browser

Input: 93
Output: [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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 ] [368 369 370…

Code:
generateMatrix : function(A){
var spiralMatrix = [];
var count = 0;
var x = 0;
var y = 0;
var done = false;
var dir = “xp”;

  while (!done) {
    if (dir === "xp") {
      if (!spiralMatrix[y]) spiralMatrix[y] = [];
      if (!spiralMatrix[y][x]) spiralMatrix[y][x] = ++count;
      x++; // last increment

      if (x === A || (spiralMatrix[y] && spiralMatrix[y][x])) {
        dir = "yp";
        x--; // reset last increment
        y++; // increment for next direction
      }
    }

    if (dir === "yp") {
      if (!spiralMatrix[y]) spiralMatrix[y] = [];
      if (!spiralMatrix[y][x]) spiralMatrix[y][x] = ++count;
      y++;

      if (y === A || (spiralMatrix[y] && spiralMatrix[y][x])) {
        dir = "xn";
        y--;
        x--;
      }
    }

    if (dir === "xn") {
      if (!spiralMatrix[y]) spiralMatrix[y] = [];
      if (!spiralMatrix[y][x]) spiralMatrix[y][x] = ++count;

      x--;

      if (x === -1 || (spiralMatrix[y] && spiralMatrix[y][x])) {
        dir = "yn";
        x++;
        y--;
      }
    }

    if (dir === "yn") {
      if (!spiralMatrix[y]) spiralMatrix[y] = [];
      if (!spiralMatrix[y][x]) spiralMatrix[y][x] = ++count;

      y--;

      if (y === -1 || (spiralMatrix[y] && spiralMatrix[y][x])) {
        dir = "xp";
        y++;
        x++;
      }
    }

    if (spiralMatrix[y] && spiralMatrix[y][x]) {
      done = true;
    }
  }

  return spiralMatrix;
}