Exercise 11: Rotate Array Left/Right

Problem Statement

Create a function `rotate(arr, n, direction="right")` that rotates array by n positions. Example: rotate([1, 2, 3, 4], 1) → [4, 1, 2, 3]

Sample Output:

rotate([1, 2, 3, 4], 1) => [4, 1, 2, 3]
rotate([1, 2, 3, 4], 1, "left") => [2, 3, 4, 1]

Solution

const rotate = (arr, n, direction = "right") => {
  const len = arr.length;
  if (len === 0) return arr;
  const k = n % len;
  if (direction === "right") return [...arr.slice(-k), ...arr.slice(0, -k)];
  return [...arr.slice(k), ...arr.slice(0, k)];
};

Explanation

Overall Goal:

  • Array ko rotate karna (left/right).

Real world:

  • Data structures: circular buffers.
  • UI: carousel rotations.