Skip to content

Commit 6ec0b96

Browse files
feat: add array rotate algorithm
1 parent 5c39e87 commit 6ec0b96

2 files changed

Lines changed: 74 additions & 0 deletions

File tree

‎Data-Structures/Array/Rotate.js‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @function rotate
3+
* @description Rotates an array to the right by k positions.
4+
* Elements that fall off the end are placed at the beginning.
5+
* @param {Array} arr - The input array
6+
* @param {number} k - Number of positions to rotate right
7+
* @returns {Array} - The rotated array
8+
* @see https://en.wikipedia.org/wiki/Circular_shift
9+
* @example rotate([1, 2, 3, 4, 5], 2) => [4, 5, 1, 2, 3]
10+
* @example rotate([1, 2, 3], 1) => [3, 1, 2]
11+
* @example rotate([1, 2, 3], 3) => [1, 2, 3]
12+
*/
13+
const rotate = (arr, k) => {
14+
if (!Array.isArray(arr)) {
15+
throw new TypeError('First argument must be an array')
16+
}
17+
if (!Number.isInteger(k)) {
18+
throw new TypeError('Second argument must be an integer')
19+
}
20+
if (arr.length === 0) return []
21+
const steps = ((k % arr.length) + arr.length) % arr.length
22+
return [...arr.slice(arr.length - steps), ...arr.slice(0, arr.length - steps)]
23+
}
24+
25+
export { rotate }
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import { rotate } from '../Rotate.js'
2+
3+
describe('rotate', () => {
4+
test('rotate([1,2,3,4,5], 2) returns [4,5,1,2,3]', () => {
5+
expect(rotate([1, 2, 3, 4, 5], 2)).toEqual([4, 5, 1, 2, 3])
6+
})
7+
8+
test('rotate([1,2,3], 1) returns [3,1,2]', () => {
9+
expect(rotate([1, 2, 3], 1)).toEqual([3, 1, 2])
10+
})
11+
12+
test('rotate([1,2,3], 3) returns [1,2,3]', () => {
13+
expect(rotate([1, 2, 3], 3)).toEqual([1, 2, 3])
14+
})
15+
16+
test('rotate([1,2,3], 0) returns [1,2,3]', () => {
17+
expect(rotate([1, 2, 3], 0)).toEqual([1, 2, 3])
18+
})
19+
20+
test('rotate with k larger than array length', () => {
21+
expect(rotate([1, 2, 3], 4)).toEqual([3, 1, 2])
22+
})
23+
24+
test('rotate with negative k rotates left', () => {
25+
expect(rotate([1, 2, 3, 4, 5], -2)).toEqual([3, 4, 5, 1, 2])
26+
})
27+
28+
test('rotate empty array returns empty array', () => {
29+
expect(rotate([], 3)).toEqual([])
30+
})
31+
32+
test('rotate single element returns same array', () => {
33+
expect(rotate([1], 5)).toEqual([1])
34+
})
35+
36+
test('rotate does not mutate original array', () => {
37+
const arr = [1, 2, 3, 4, 5]
38+
rotate(arr, 2)
39+
expect(arr).toEqual([1, 2, 3, 4, 5])
40+
})
41+
42+
test('throws TypeError for non-array input', () => {
43+
expect(() => rotate('123', 2)).toThrow(TypeError)
44+
})
45+
46+
test('throws TypeError for float k', () => {
47+
expect(() => rotate([1, 2, 3], 1.5)).toThrow(TypeError)
48+
})
49+
})

0 commit comments

Comments
 (0)