1var generateMatrix = function (n) {2const arr = new Array(n).fill(0).map(() => new Array(n).fill(0));3let count = 1,4index = 1,5i = 0,6j = 0,7changed = false,8toIncrease = true;9arr[i][j] = index;10while (index < n * n) {11index++;12if (i == n - count && j > count - 1) {13j--;14toIncrease = false;15changed = true;16} else if (i !== n - count && j == n - count) {17i++;18toIncrease = false;19changed = true;20}21if (i == count - 1 && !changed) {22if (toIncrease) j++;23else j--;24} else if (j == count - 1 && !changed) {25if (i == count) {26toIncrease = true;27j++;28count++;29} else if (toIncrease) i++;30else i--;31}32arr[i][j] = index;33if (index == 4 * (n - 1)) {34toIncrease = true;35count++;36}37changed = false;38}39return arr;40};