rotate

Rotates the elements of an array by a given number of positions.

1. Code

/**
 * Rotates an array in the specified direction by a given number of positions.
 *
 * @param arr - The array to rotate.
 * @param n - The number of positions to rotate the array by.
 * @param dir - The direction in which to rotate the array. Defaults to "left".
 * @returns The rotated array.
 * @template T - The type of elements in the array.
 */
const rotate = <T>(
  arr: T[],
  n: number,
  dir: "left" | "right" = "left"
): T[] => {
  if (dir === "left") {
    return arr.slice(n, arr.length).concat(arr.slice(0, n));
  } else {
    return arr
      .slice(arr.length - n, arr.length)
      .concat(arr.slice(0, arr.length - n));
  }
};

export default rotate;

2. Installation

npx @jrtilak/lazykit@latest add rotate -ts

3. Description

The rotate function takes an array and a number as arguments, and returns a new array that is a rotated version of the original array. The rotation is performed by shifting the elements of the array to the left by the number of positions specified by the second argument.

4. Props

Prop

Type

Default Value

array*array---
position*number---
directionenumleft

5. Examples

import rotate from ".";

const arr = [1, 2, 3, 4, 5];
rotate(arr, 2);
// Expected Output: [3, 4, 5, 1, 2]

rotate(arr, 2, "right");
// Expected Output: [4, 5, 1, 2, 3]