In-Place Matrix Rotation By 90 Degrees

Rotate a square matrix clockwise or counter-clockwise in place using a transpose and row reversal, with square-shape validation.

JavascriptData Integrity

Code

javascriptsnippet
27 lines
export function rotateMatrix(matrix, direction = "clockwise") {
  if (!Array.isArray(matrix)) throw new TypeError("matrix must be an array");
  if (direction !== "clockwise" && direction !== "counterclockwise") {
    throw new RangeError("direction must be clockwise or counterclockwise");
  }
  const size = matrix.length;
  for (const row of matrix) {
    if (!Array.isArray(row) || row.length !== size) {
      throw new RangeError("matrix must be square");
    }
  }

  for (let row = 0; row < size; row += 1) {
    for (let column = row + 1; column < size; column += 1) {
      const temporary = matrix[row][column];
      matrix[row][column] = matrix[column][row];
      matrix[column][row] = temporary;
    }
  }

  if (direction === "clockwise") {
    for (const row of matrix) row.reverse();
  } else {
    matrix.reverse();
  }
  return matrix;
}

What the code does

Count the function rotateMatrix as the entire surface area of In-Place Matrix Rotation By 90 Degrees.

The nesting pairs for (const row of matrix) with for (let row = 0; row < size; row += 1) — the inner runs once per outer step. A guard precedes the TypeError and RangeError: bad state stops the flow there instead of continuing.

The input matrix is mutated in place — callers that need the original must pass a copy.

Caveats

  • The guard direction !== "clockwise" && direction !== "counterclockwise" short-circuits the flow with an early throw when its condition holds.
  • matrix is mutated in place — the value you pass will not be the same afterward.

Applying it

The main signature reads export function rotateMatrix(matrix, direction = "clockwise")

The surface worth importing is rotateMatrix; the helpers around it are private to the snippet.

Statements that matter

if (!Array.isArray(matrix)) throw new TypeError("matrix must be an array");
throw new RangeError("direction must be clockwise or counterclockwise");
for (let column = row + 1; column < size; column += 1) {
const temporary = matrix[row][column];
matrix[row][column] = matrix[column][row];
matrix[column][row] = temporary;
}

Interactive Tools for This Topic

FAQ

Does `rotateMatrix` modify its input?
Yes — `matrix` is mutated in place. Pass a copy if the caller needs the original preserved.
How does the snippet fail?
It throws `TypeError` and `RangeError` before any real work runs, via the guard `direction !== "clockwise" && direction !== "counterclockw…` — handle it at the call site or let it propagate deliberately.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `rotateMatrix` at load time.