Rotate a rectangular grid by any number of quarter turns
A puzzle game lets players rotate tiles with the Q and E keys. Each tile is a grid of cells, tiles are often wider than they are tall, and players can mash a key many times before the board re-renders, so the game sends one total turn count.
Implement rotateGrid(grid, turns). It returns a new grid rotated by turns quarter turns (90 degrees each).
rotateGrid(grid, turns = 1) // => new grid
grid is an array of rows. Every row has the same, non-zero length, so a grid with R rows and C columns is R × C. An empty grid ([]) rotates to [].turns rotates clockwise, a negative one rotates counter-clockwise. turns defaults to 1 and can be any integer: four turns in the same direction bring the grid back to where it started.R × C grid gives a C × R grid. Two quarter turns keep the size.turns = 0). Do not change grid. Cell values are copied as is.rotateGrid([
[1, 2, 3],
[4, 5, 6],
]);
// => [
// [4, 1],
// [5, 2],
// [6, 3],
// ]
rotateGrid([
['a', 'b'],
['c', 'd'],
], -1);
// => [
// ['b', 'd'],
// ['a', 'c'],
// ]
rotateGrid([[1, 2, 3]], 2); // => [[3, 2, 1]]
rotateGrid([[1, 2, 3]], 7); // same as 3 turns (or -1): [[3], [2], [1]]
rotateGrid([], 5); // => []