Skip to content

Commit 4dff73a

Browse files
Merge pull request #82 from nathzz30/rotateToRightArray
Created a function rotation to made the rotation of an array #53 and #52
2 parents a9d88ea + be2bbf8 commit 4dff73a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Array/Rotation.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* A function that takes 3 parameters to make a rotation in an array.
3+
* @example arr=[1,2,3,4,5,6,7,8,9], rotation(arr, 3, "right") returns [4,5,6,7,8,9,1,2,3]
4+
* @function
5+
* @param {Array} arr - The array to rotate.
6+
* @param {Number} n - The number of rotations.
7+
* @param {string} direction - The direction of the rotation.
8+
* @returns {Array}
9+
*/
10+
11+
const rotation = (arr, n, direction) => {
12+
if (direction === "right") {
13+
for (let i = 0; i < n; i++) {
14+
let firstElement = arr.shift();
15+
arr.push(firstElement);
16+
}
17+
} else {
18+
for (let i = 0; i < n; i++) {
19+
let lastElement = arr.pop();
20+
arr.unshift(lastElement);
21+
}
22+
}
23+
return arr;
24+
};
25+
26+
export default rotation;

0 commit comments

Comments
 (0)