How to rotate a matrix in JavaScript

Here is one way of rotating a matrix in-place using JavaScript.
Space complexity: O(1).
Time complexity: O(n^2).

rotateMatrixTry in REPL
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
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]
// left -> top
matrix[first][i] = matrix[last-offset][first];
// bottom -> left
matrix[last-offset][first] = matrix[last][last-offset];
// right -> bottom
matrix[last][last-offset] = matrix[i][last];
// top -> right
matrix[i][last] = top; // right <- saved top
} else if (rotateCounterClockwise) {
const left = matrix[last-offset][first];
// top -> left
matrix[last-offset][first] = matrix[first][i]
// right -> top
matrix[first][i] = matrix[i][last];
// bottom -> right
matrix[i][last] = matrix[last][last-offset];
// left -> bottom
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]]; // swap values
}
}
}
function reverseRows(matrix) {
for (let i = 0; i < matrix.length; i++) {
const row = matrix[i];
row.reverse();
}
}
rotate = geometricRotate;

Tests can be found at REPL.it