Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Data-Structures/Array/Rotate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* @function rotate
* @description Rotates an array to the right by k positions.
* Elements that fall off the end are placed at the beginning.
* @param {Array} arr - The input array
* @param {number} k - Number of positions to rotate right
* @returns {Array} - The rotated array
* @see https://en.wikipedia.org/wiki/Circular_shift
* @example rotate([1, 2, 3, 4, 5], 2) => [4, 5, 1, 2, 3]
* @example rotate([1, 2, 3], 1) => [3, 1, 2]
* @example rotate([1, 2, 3], 3) => [1, 2, 3]
*/
const rotate = (arr, k) => {
if (!Array.isArray(arr)) {
throw new TypeError('First argument must be an array')
}
if (!Number.isInteger(k)) {
throw new TypeError('Second argument must be an integer')
}
if (arr.length === 0) return []
const steps = ((k % arr.length) + arr.length) % arr.length
return [...arr.slice(arr.length - steps), ...arr.slice(0, arr.length - steps)]
}

export { rotate }
49 changes: 49 additions & 0 deletions Data-Structures/Array/test/Rotate.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { rotate } from '../Rotate.js'

describe('rotate', () => {
test('rotate([1,2,3,4,5], 2) returns [4,5,1,2,3]', () => {
expect(rotate([1, 2, 3, 4, 5], 2)).toEqual([4, 5, 1, 2, 3])
})

test('rotate([1,2,3], 1) returns [3,1,2]', () => {
expect(rotate([1, 2, 3], 1)).toEqual([3, 1, 2])
})

test('rotate([1,2,3], 3) returns [1,2,3]', () => {
expect(rotate([1, 2, 3], 3)).toEqual([1, 2, 3])
})

test('rotate([1,2,3], 0) returns [1,2,3]', () => {
expect(rotate([1, 2, 3], 0)).toEqual([1, 2, 3])
})

test('rotate with k larger than array length', () => {
expect(rotate([1, 2, 3], 4)).toEqual([3, 1, 2])
})

test('rotate with negative k rotates left', () => {
expect(rotate([1, 2, 3, 4, 5], -2)).toEqual([3, 4, 5, 1, 2])
})

test('rotate empty array returns empty array', () => {
expect(rotate([], 3)).toEqual([])
})

test('rotate single element returns same array', () => {
expect(rotate([1], 5)).toEqual([1])
})

test('rotate does not mutate original array', () => {
const arr = [1, 2, 3, 4, 5]
rotate(arr, 2)
expect(arr).toEqual([1, 2, 3, 4, 5])
})

test('throws TypeError for non-array input', () => {
expect(() => rotate('123', 2)).toThrow(TypeError)
})

test('throws TypeError for float k', () => {
expect(() => rotate([1, 2, 3], 1.5)).toThrow(TypeError)
})
})
Loading