rotate

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

1. Code

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

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]