Rotate Image

You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise).

Example 1: 
Given input matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

Solution using Javascript:

 
const swap = (matrix, x1, y1, x2, y2) => {
  const temp = matrix[x1][y1];
  matrix[x1][y1] = matrix[x2][y2];
  matrix[x2][y2] = temp;
};
 
 
const rotate = (matrix) => {
  const row = matrix.length;
  const column = matrix[0].length;
  if (row === 0) {
    return;
  }
  // swap Diagonaly
  for (let i = 0; i < row; i += 1) {
    for (let j = 0; j < column - i; j += 1) {
      swap(matrix, i, j, row - 1 - j, column - 1 - i);
    }
  }
  for (let i = 0; i < Math.floor(row / 2); i += 1) {
    for (let j = 0; j < column; j += 1) {
      swap(matrix, i, j, row - 1 - i, j);
    }
  }
  
  return matrix;
};
 

Test Case

describe('rotate', () => {
  test('should return rotated array', () => {
    const myArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
    expect(rotate(myArray)).toEqual([[7, 4, 1], [8, 5, 2], [9, 6, 3]]);
  });
});