-
Notifications
You must be signed in to change notification settings - Fork 111
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Created a funtion rotation to made the rotation of an array
- Loading branch information
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
/** | ||
* A function that takes 3 parameters to make a rotation in an array. | ||
* @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] | ||
* @function | ||
* @param {Array} arr - The array to rotate. | ||
* @param {Number} n - The number of rotations. | ||
* @param {string} direction - The direction of the rotation. | ||
* @returns {Array} | ||
*/ | ||
|
||
const rotation = (arr, n, direction) => { | ||
if (direction === "right") { | ||
for (let i = 0; i < n; i++) { | ||
let firstElement = arr.shift(); | ||
arr.push(firstElement); | ||
} | ||
} else { | ||
for (let i = 0; i < n; i++) { | ||
let lastElement = arr.pop(); | ||
arr.unshift(lastElement); | ||
} | ||
} | ||
return arr; | ||
}; | ||
|
||
export default rotation; |