rotate<T> function

void rotate<T>(
  1. List<T> list,
  2. int n
)

Rotates the order of the elements in the list in such a way that the element at index n becomes the new first element.

n can be positive or negative (for right-ward wrapping).

Example:

final list = [1, 2, 3, 4, 5];
rotate(list, 2); // list is now [3, 4, 5, 1, 2]

Implementation

void rotate<T>(List<T> list, int n) {
  if (list.isEmpty) return;
  n = n % list.length;
  if (n < 0) n += list.length;
  if (n == 0) return;

  _reverseRange(list, 0, n);
  _reverseRange(list, n, list.length);
  _reverseRange(list, 0, list.length);
}