function rotate(matrix, rotateCounterClockwise=false) {
rotateClockwise = !rotateCounterClockwise;
if (matrix.length === 0 || matrix.length !== matrix[0].length) return false;
const n = matrix.length;
for (let layer = 0; layer < Math.floor(n / 2); layer++) {
const first = layer;
const last = n - 1 - layer;
for (let i = first; i < last; i++) {
const offset = i - first;
if (rotateClockwise) {
const top = matrix[first][i]
matrix[first][i] = matrix[last-offset][first];
matrix[last-offset][first] = matrix[last][last-offset];
matrix[last][last-offset] = matrix[i][last];
matrix[i][last] = top;
} else if (rotateCounterClockwise) {
const left = matrix[last-offset][first];
matrix[last-offset][first] = matrix[first][i]
matrix[first][i] = matrix[i][last];
matrix[i][last] = matrix[last][last-offset];
matrix[last][last-offset] = left;
}
}
}
return matrix;
}
function geometricRotate(matrix, rotateCounterClockwise=false) {
if (matrix.length === 0 || matrix.length !== matrix[0].length) return false;
rotateClockwise = !rotateCounterClockwise;
if (rotateClockwise) {
transpose(matrix)
reverseRows(matrix);
} else if (rotateCounterClockwise) {
reverseRows(matrix)
transpose(matrix);
}
return matrix;
}
function transpose(matrix) {
for (let i = 0; i < matrix.length; i++) {
for (j = 0; j < i; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
}
function reverseRows(matrix) {
for (let i = 0; i < matrix.length; i++) {
const row = matrix[i];
row.reverse();
}
}
rotate = geometricRotate;