rotate

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

1.
/**
2.
* Rotates the elements of an array by a given number of positions.
3.
**/
4.
const rotate = <T,>(
5.
arr: T[],
6.
n: number,
7.
dir: 'left' | 'right' = 'left',
8.
): T[] => {
9.
if (dir === 'left') {
10.
return arr.slice(n, arr.length).concat(arr.slice(0, n));
11.
} else {
12.
return arr
13.
.slice(arr.length - n, arr.length)
14.
.concat(arr.slice(0, arr.length - n));
15.
}
16.
};
17.
18.
export default rotate;

1. Installtion

npx @jrtilak/lazykit add rotate

2. Parameters

  • arr (T[])
    The array whose elements will be rotated.

  • n (number)
    The number of positions to rotate the array. A positive number indicates the number of positions to rotate.

  • dir (optional) ("left" | "right")
    The direction to rotate the elements. Defaults to "left". If set to "right", the elements will be rotated in the opposite direction.

3. Returns

  • T[]
    Returns a new array with the elements rotated by the specified number of positions in the specified direction. The original array remains unchanged.

4. Type Parameters

  • T
    The type of elements in the array. This allows the function to work with arrays of any type, ensuring type safety for the rotated elements.

5. Usage

1. Left Rotation by 2 Positions

1.
import rotate from '@/helpers/rotate';
2.
3.
const numbers = [1, 2, 3, 4, 5];
4.
const result1 = rotate(numbers, 2, "left");
5.
6.
console.log(result1);
7.
// Output: [3, 4, 5, 1, 2]

2. Right Rotation by 3 Positions

1.
import rotate from '@/helpers/rotate';
2.
3.
const numbers = [1, 2, 3, 4, 5];
4.
const result2 = rotate(numbers, 3, "right");
5.
6.
console.log(result2);
7.
// Output: [3, 4, 5, 1, 2]

3. Left Rotation by Default

1.
import rotate from '@/helpers/rotate';
2.
3.
const numbers = [10, 20, 30, 40, 50];
4.
const result3 = rotate(numbers, 1);
5.
6.
console.log(result3);
7.
// Output: [20, 30, 40, 50, 10]