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

snippet
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;
}