-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathRotateArray.js
More file actions
61 lines (49 loc) · 1.62 KB
/
RotateArray.js
File metadata and controls
61 lines (49 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Rotates an array to the right by k positions
* @see https://en.wikipedia.org/wiki/Circular_shift
* @param {number[]} array - The array to rotate
* @param {number} k - Number of positions to rotate
* @returns {number[]} - New array rotated to the right by k positions
* @throws {TypeError} - If input is not an array
*/
const rotateRight = (array, k) => {
if (!Array.isArray(array)) {
throw new TypeError('Input must be an array')
}
if (!Number.isInteger(k) || k < 0) {
throw new TypeError('Rotation count must be a non-negative integer')
}
const length = array.length
if (length === 0) return []
const normalizedK = k % length
const rotated = new Array(length)
for (let i = 0; i < length; i++) {
rotated[(i + normalizedK) % length] = array[i]
}
return rotated
}
/**
* Rotates an array to the left by k positions
* @see https://en.wikipedia.org/wiki/Circular_shift
* @param {number[]} array - The array to rotate
* @param {number} k - Number of positions to rotate
* @returns {number[]} - New array rotated to the left by k positions
* @throws {TypeError} - If input is not an array
*/
const rotateLeft = (array, k) => {
if (!Array.isArray(array)) {
throw new TypeError('Input must be an array')
}
if (!Number.isInteger(k) || k < 0) {
throw new TypeError('Rotation count must be a non-negative integer')
}
const length = array.length
if (length === 0) return []
const normalizedK = k % length
const rotated = new Array(length)
for (let i = 0; i < length; i++) {
rotated[i] = array[(i + normalizedK) % length]
}
return rotated
}
export { rotateRight, rotateLeft }